【问题标题】:create and joining websocket via laravel-echo in react app在反应应用程序中通过 laravel-echo 创建和加入 websocket
【发布时间】: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


【解决方案1】:

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

如果您需要任何澄清,请告诉我。

编辑: 看起来你的连接被称为 ch,所以你只需要将它作为道具传递给你的孩子。假设您的代码位于高级根组件/容器之一(例如 App.js)中,您会像这样传递它。

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

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

&lt;ChildComponent ch={this.echo} /&gt;

但应该是这样的:

&lt;ChildComponent ch={this.ch} /&gt;

【讨论】:

  • 感谢您的回复。我尝试通过道具做到这一点,但不成功。你能告诉我如何实现它吗?
  • 我编辑了问题并添加了更多细节。你能帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2021-12-14
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
相关资源
最近更新 更多