gpt4 book ai didi

reactjs - 在 React 应用程序中通过 laravel-echo 创建和加入 websocket

转载 作者:行者123 更新时间:2023-12-04 15:21:23 24 4
gpt4 key购买 nike

我正在使用 laravel-echo在我的 react 应用程序中创建和使用 websocket。它很容易在页面中使用 laravel-echo。但是当需要在多个页面中使用时,它会创建多个 channel 并订阅几次。如何制作单个 channel 并加入多个页面?用 Prop 什么的...

我尝试通过如下 Prop ,但出现了一些错误:

parent Component:

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} />
}

and this is child Component code :

    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);
});

}

i got this errorTypeError: Cannot read property 'here' of undefined

最佳答案

是的,在某种程度上你回答了你自己的问题。你在这里需要一个单例,所以我会在根容器中初始化连接,然后将你需要的东西作为 Prop 传递给你需要它的每个屏幕。

如果您需要任何说明,请告诉我。

编辑:看起来您的连接称为 ch,因此您只需要将其作为 Prop 传递给您的 child 。假设您的代码位于您的高级根组件/容器之一(例如 App.js)中,您会像这样将其传递下去。

<View>
<SomeChildComponent ch={this.ch} />
</View>

编辑:您这样做是为了渲染您的子组件:

<ChildComponent ch={this.echo} />

但应该是这样的:

<ChildComponent ch={this.ch} />

关于reactjs - 在 React 应用程序中通过 laravel-echo 创建和加入 websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63204174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com