【问题标题】:setState not mutating while calling a function multiple times多次调用函数时 setState 不会发生变化
【发布时间】: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


【解决方案1】:

如果您在一个循环中或在单个渲染周期内将多个状态更新排入队列,那么您通常会希望使用功能状态更新,以便从之前的状态进行更新,而 不是 some 状态值在回调范围内关闭。在您的情况下,您正在向数组 from 前一个状态添加一个新值,因此这里依赖于前一个状态。

Functional State Updates

如果新状态是使用前一个状态计算的,你可以传递一个 函数到setState。该函数将接收先前的值, 并返回一个更新的值。

setNewChannels(newChannels => newChannels.concat(newChannelMetadata))

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2023-02-08
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多