我使用pusher-js
从后端接收数据。
我在useEffect
中这样配置它:
useEffect(() => {
const pusher = new Pusher('my_app_id', {
cluster: 'us3',
});
const channel = pusher.subscribe('messages');
channel.bind('send-message', (data) => {
});
}, []);
在.bind
方法的回调中,我想访问react状态。问题是,如果它被更新,这个回调仍然有旧版本。
channel.bind('send-message', (data) => {
// here is my outdated state
});
我如何在这个回调中访问新的、更新的状态?提前感谢
在useEffect的依赖数组中使用另一个具有更新状态的useEffect,一旦状态更新,useEffect就会。被触发,在它里面你可以访问更新的状态。
我在同一个问题上困了很长时间。我最终解决这个问题的方法是存储通道,并在每次状态(我想在绑定回调中访问(更改时重新绑定事件。这里有一个代码片段可以帮助您更好地理解。
非常重要-在重新绑定事件之前,不要忘记从通道中解除绑定。因为在没有解除绑定的情况下重新绑定之前的绑定只会为事件创建额外的侦听器,当事件发生时,所有侦听器都会启动,这将是一片混乱。艰难地学习:"(
不知道这是否是最好的方法,但对我有效。
const [pusherChannel, setPusherChannel] = useState(null);
const [data, setData] = useState(null);
// TRIGGERED ON MOUNT
useEffect(() => {
const pusher = new Pusher(APP_KEY, {
cluster: APP_CLUSTER
});
const channel = pusher.subscribe(CHANNEL_NAME);
setPusherChannel(channel);
// PREVIOUSLY
// channel.bind(EVENT_NAME, (pusherData) => {
// ...
// Accessing "data" here would give the state used
// during binding the event
//});
}, []);
// TRIGGERED ON CHANGE IN "data"
useEffect(() => {
console.log("Updated data : ", data);
if(pusherChannel && pusherChannel.bind){
console.log("Unbinding Event");
pusherChannel.unbind(EVENT_NAME);
console.log("Rebinding Event");
pusherChannel.bind(EVENT_NAME, (pusherData) => {
// USE UPDATED "data" here
}
}
}, [pusherChannel, data]);
参考-
- 绑定事件
- 取消绑定事件