私は反応アプリでwebsocketを作成して使用するためにlaravel-echoを使用しています。ページで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);
});
}