我在 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]);
最佳答案
这里有两种选择
- 将
chat
状态添加到useEffect 依赖数组
,这样它就知道它依赖于chat
。
useEffect(() => {
if (connection) {
//...
setChat([...chat, newMsg]); // issue with this line. chat is always empty
//...
}
}, [connection, chat]);
- 使用
setState 回调
来更新chat
,这样你就不会得到stale data
useEffect(() => {
if (connection) {
//...
setChat((ch) => [...ch, newMsg]); // issue with this line. chat is always empty
//...
}
}, [connection]);
第二种方式更合适。
关于reactjs - react useState,useEffect中的setState不更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65719838/