【发布时间】:2021-10-25 09:09:00
【问题描述】:
我正在使用 PubNub SDK 来实现与 React 组件的聊天.. 由于设置状态的异步性质,我一直在刷新状态。下面是一些代码来说明这是如何工作的。
const handleNewChannelCreation = async (newChannelId: string) => {
const newChannelMetadata = (await pubnub.objects.getChannelMetadata({ channel: newChannelId })).data
setCurrentChannelMetadata(newChannelMetadata ? newChannelMetadata : dummyChannelMetadata)
if (channelMetadata) {
const filteredChannels = channelMetadata.filter(isChannel)
const isNewChannel = filteredChannels.findIndex((channel) => channel.id === newChannelMetadata.id)
// the api can return an existing channel therefore we need to check if the channel already exists
if (isNewChannel === -1) {
console.log("handleNewChannelCreation__", filteredChannels.length, "newChannel", newChannelMetadata.name)
setNewChannels(newChannels.concat(newChannelMetadata)) // this is not ideal I know and this dont work as this function is called multiple times.
}
}
setIsModalOpen(false)
}
【问题讨论】:
-
不完全确定您要做什么,但听起来您想根据先前的状态更改设置状态,但您需要确保首先保留先前的状态更改。您需要监听这些状态更改事件,并且仅在收到该回调时才响应。如果您希望快速解决此问题,我会将此问题发送到 support@pubnub.com,并附上 SDK 日志和完整代码。免费支持是最好的努力,但它仍然很及时。
标签: javascript reactjs chat setstate pubnub