【发布时间】:2020-11-22 00:41:35
【问题描述】:
我正在使用 laravel-echo 在我的 react-app 中创建和使用 websocket。 它易于在页面中使用 laravel-echo。但是当需要在多个页面中使用时,它会创建多个频道并订阅几次。 如何制作一个频道并加入多个页面?用道具什么的……
我尝试通过下面的道具,但出现了一些错误:
父组件:
import Echo from 'laravel-echo';
const token = window.localStorage.getItem('access_token');
const options = {
broadcaster: 'pusher',
key: '7890165486',
wsHost: '45.149.78.4',
wsPort: 6001,
disableStats: true,
authEndpoint: 'http://xxx.xxx.net/broadcasting/auth',
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json'
}
}
};
const echo = new Echo(options);
Class ParentComponnet extends Component {
componentDidMount() {
this.EchoJoin();
}
EchoJoin() {
let ch = echo.join(`chat.${this.props.token}`);
ch
.here((user) => {
console.log('all online use', user);
})
.joining((user) => {
alert(user.id + ' New Join the Channel');
})
.leaving((user) => {
alert(user.id + ' Leave the Channel');
})
.listen('MessageSent', (e) => {
console.log('>>>>>>>>>>>>', e);
});
}
<ChildComponent ch={this.echo} />
}
这是子组件代码:
componentDidMount() {
this.props.ch
.here((user) => {
console.log('all online use', user);
})
.joining((user) => {
alert(user.id + ' New Join the Channel');
})
.leaving((user) => {
alert(user.id + ' Leave the Channel');
})
.listen('MessageSent', (e) => {
console.log('>>>>>>>>>>>>', e);
});
}
【问题讨论】:
-
ch 未定义。这意味着它从未作为道具传下来。当您调用正在使用 ch 的组件并出现错误时显示您的代码。
-
谢谢你亲爱的道格·沃特金斯。我编辑了问题,所以它以干净的方式显示代码
标签: reactjs react-native websocket laravel-echo pusher-js