【问题标题】:React useState, setState in useEffect not updating array反应useState,useEffect中的setState不更新数组
【发布时间】:2021-04-19 12:33:02
【问题描述】:

我在 SO 上看到过这个问题,但我似乎无法弄清楚它存在的原因。

我正在学习here的教程

我正在使用 useState,但是当我尝试更新状态时,数组为空。我使用状态最初创建一个空数组。收到消息后,我尝试使用扩展运算符将消息添加到数组中,我已经无数次使用该运算符将对象添加到数组中(但从未在 useEffect 中)。

如果我取消注释注释行,“聊天”会按应有的方式更新,但我不明白为什么传播运算符不工作,我需要使用 useRef 来完成这项工作。我不想为每个相应的 useState 加载大量的 useRef(至少不知道为什么有必要)

谁能看到我做错了什么,或者解释我为什么需要 useRef?

const [chat, setChat ] = useState([]);

//const latestChat = useRef(null);
//latestChat.current = chat;

// ...

useEffect(() => {
    if (connection) {
        connection.start()
            .then(result => {
                console.log('Connected!');

                connection.on('ReceiveMessage', message => {
                    const newMsg = {
                        user: message.user,
                        message:message.message
                    }
                    setChat([...chat, newMsg]); // issue with this line. chat is always empty

                    //const updatedChat = [...latestChat.current];
                    //updatedChat.push(message);
                    //setChat(updatedChat);
                    
                    
                });
            })
            .catch(e => console.log('Connection failed: ', e));
    }
}, [connection]);

【问题讨论】:

  • 你应该使用setChat(chat => [...chat, newMsg])而不是setChat([...chat, newMsg])
  • 你试过我的解决方案了吗?
  • @TaghiKhavari - 我在发布之前尝试了第一种方法,但它对我不起作用。我将很快尝试第二种方式,但仍然很困惑为什么我的代码在 useEffect 中不起作用但在常规函数中起作用但谢谢

标签: reactjs react-hooks use-effect


【解决方案1】:

这里有两种选择

  1. chat 状态添加到useEffect dependency array,这样它就知道它依赖于chat
useEffect(() => {
  if (connection) {
    //...
    setChat([...chat, newMsg]); // issue with this line. chat is always empty
    //...
  }
}, [connection, chat]);
  1. 使用setState callback 更新chat 这样你就不会得到stale data
useEffect(() => {
  if (connection) {
    //...
    setChat((ch) => [...ch, newMsg]); // issue with this line. chat is always empty
    //...
  }
}, [connection]);

第二种方式更合适。

【讨论】:

  • 一百万谢谢。第二个选项完美地工作。立即搜索您的关键词以了解更多信息。感谢您强调它们。
  • @grayson 很高兴我能帮上忙,干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2020-10-16
  • 2021-07-12
  • 2021-10-04
  • 2021-09-06
  • 2021-03-23
相关资源
最近更新 更多