3

i am using laravel-echo to create and use websocket in my react-app. its easy to use laravel-echo in a page. but when need to use in several pages, it make several channel and subscribe several time. how to make a single channel and join ones in several pages ? with props or something ...

i try via props like below but there was some error:

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 error TypeError: Cannot read property 'here' of undefined

4

1 回答 1

2

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

如果您需要对此进行任何澄清,请告诉我。

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

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

编辑:您这样做是为了呈现您的子组件:

<ChildComponent ch={this.echo} />

但应该是这样的:

<ChildComponent ch={this.ch} />

于 2020-08-04T16:07:20.023 回答