提问人:Afeef 提问时间:11/16/2023 最后编辑:Drew ReeseAfeef 更新时间:11/16/2023 访问量:24
React Native + Redux 中的 Pusher 通道不使用更新状态
Pusher channel in React Native + Redux does not use updated state
问:
我正在使用 pusher-websocket-react-native 为 Expo 上的移动应用程序创建实时聊天。
我注意到,每当我订阅一个状态通道时,它都会保持自己的状态,这意味着当 Redux 存储中发生状态更改时,通道的 onEvent 不会使用最新值。
const {
selectedChatRoom, // <--- When a state change occurs here...
// ...
} = useSelector(state => state.chat, shallowEqual);
useEffect(() => {
console.log(selectedChatRoom); // <--- This one uses new value
}, [selectedChatRoom]}
// ...
const onEvent = (event) => {
switch (event.eventName) {
case bindingKeys.chat.message:
onMessageReceived(event);
break;
default:
break;
}
};
const onMessageReceived = (event) => {
// ...
const chatRoomId = event.data.chatRoomId;
const isChatRoomOpen = selectedChatRoom?._id === chatRoomId; // <--- This one maintains old value
// ...
};
目前,我正在通过取消订阅然后再次订阅(基于此线程,但 React Native 中没有 Pusher 的取消绑定和绑定)来更新状态来处理这个问题,但我认为这不是一个好的解决方案。有谁知道我可以尝试的任何其他解决方案?关于这个问题,React Native似乎没有太多参考。
// Current solution
const resubscribeToChannels = async () => {
if (selectedChatRoom?._id === undefined) return;
await pusher
.unsubscribe({
channelName: `presence-${selectedChatRoom?._id}`,
})
.then(async () => {
await pusher.subscribe({
channelName: `presence-${selectedChatRoom?._id}`,
onEvent, // <--- I believe this rebinds the event to the current state
// but will maintain this state until another re-subscription
});
}
);
};
useEffect(() => {
resubscribeToChannels();
}, [selectedChatRoom]);
答: 暂无答案
评论