在 React 中插入 Laravel Echo
Insert Laravel Echo in React
我有以下脚本在 welcome.blade.php
中完美运行:
<script>
Echo.channel('home')
.listen('NewPatient',(e) => {console.log(e.patient);
})
</script>
Home
是频道名称,NewPatient
是事件名称。
如何在 React 组件中实现此脚本以便我可以在该组件中精确显示数据?
患者组件 反应:
import React,{Component} from 'react';
import axios from 'axios';
import Echo from "laravel-echo";
class Patient extends React.Component {
constructor(props) {
super(props);
this.state = {
patients : []
};
}
componentDidMount() {
axios.get('api/patients')
.then(response => {this.setState({patients: response.data})})
.catch(err => console.log(err));
}
render() {
return (
<ul>
{ this.state.patients.map(patient => <li>{patient.nom}</li>)}
</ul>
)
}
}
export default Patient;
当我尝试将脚本粘贴到ComponentDidMount区域时,出现laravel_echo__WEBPACK_IMPORTED_MODULE_2__.default.channel
和Can't perform a React state update on an unmounted component
[=等错误35=]
已解决!在我的 ComponentDidmount
代码中的 Echo 旁边添加了 window.
window.Echo.channel('home')
.listen('NewPatient',(e) => {console.log(e.patient);
})
我有以下脚本在 welcome.blade.php
中完美运行:
<script>
Echo.channel('home')
.listen('NewPatient',(e) => {console.log(e.patient);
})
</script>
Home
是频道名称,NewPatient
是事件名称。
如何在 React 组件中实现此脚本以便我可以在该组件中精确显示数据?
患者组件 反应:
import React,{Component} from 'react';
import axios from 'axios';
import Echo from "laravel-echo";
class Patient extends React.Component {
constructor(props) {
super(props);
this.state = {
patients : []
};
}
componentDidMount() {
axios.get('api/patients')
.then(response => {this.setState({patients: response.data})})
.catch(err => console.log(err));
}
render() {
return (
<ul>
{ this.state.patients.map(patient => <li>{patient.nom}</li>)}
</ul>
)
}
}
export default Patient;
当我尝试将脚本粘贴到ComponentDidMount区域时,出现laravel_echo__WEBPACK_IMPORTED_MODULE_2__.default.channel
和Can't perform a React state update on an unmounted component
[=等错误35=]
已解决!在我的 ComponentDidmount
代码中的 Echo 旁边添加了window.
window.Echo.channel('home')
.listen('NewPatient',(e) => {console.log(e.patient);
})