我正在使用拉拉回声创建和使用websocket在我的反应-应用程序。这是很容易使用的拉拉回声在一页。但是当需要在几个页面中使用时,它会制作几个频道,订阅几次。如何在几个页面中建立一个单一的通道并将它们连接起来?有道具之类的.
我试着用下面的道具,但是有一些错误:
父组件:
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);
});
}我犯了这个错误

发布于 2020-08-04 16:07:20
是的,在某种程度上你回答了你自己的问题。这里需要一个单例,所以我将在根容器中初始化连接,然后将所需的内容传递给每个需要它的屏幕。
如果你需要澄清的话请告诉我。
编辑:看起来你的连接被称为ch,所以你只需要把它传递给你的孩子作为道具。假设您的代码在一个高级根组件/容器(如App.js )中,您将以这样的方式传递它。
<View>
<SomeChildComponent ch={this.ch} />
</View>编辑:您这样做是为了呈现您的子组件:
<ChildComponent ch={this.echo} />
但应该是这样:
<ChildComponent ch={this.ch} />
https://stackoverflow.com/questions/63204174
复制相似问题