【发布时间】: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