反应 useState,useEffect 中的 setState 不更新数组 [英] React useState, setState in useEffect not updating array
问题描述
我在 SO 上看到过这个问题,但我似乎无法弄清楚它为什么存在.
I've seen this problem on SO, but I cannot seem to work out why it exists.
我正在学习 这里
我正在使用 useState 但当我尝试更新状态时,数组为空.我正在使用 state 最初创建一个空数组.在收到消息时,我尝试使用扩展运算符将消息添加到数组中,我已经无数次使用该运算符将对象添加到数组中(但从未在 useEffect 中使用过).
I am using useState but when I try to update the state, the array is empty. I am using state to create initially an empty array. on message received, I am trying to add the message to the array, using the spread operator, which I have used countless times to add an object to an array (but never inside useEffect).
如果我取消注释注释行,聊天"得到更新,但我不明白为什么传播运算符不起作用,我需要使用 useRef 来完成这项工作.我不想为每个相应的 useState 加载大量 useRef(至少不知道为什么需要)
If I uncomment the commented lines, "chat" gets updated as it should do, but I cannot understand why the spread operator is not working and I need to use a useRef to make this work. I don't want to have loads of useRef for every corresponding useState (at least not knowing why it is necessary)
谁能看到我做错了什么,或者解释为什么我需要 useRef?
Can anyone see what I am doing wrong, or explain why I need the 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
.
- add
chat
state touseEffect dependency array
so it knows it depends onchat
.
useEffect(() => {
if (connection) {
//...
setChat([...chat, newMsg]); // issue with this line. chat is always empty
//...
}
}, [connection, chat]);
- 使用
setState回调
来更新chat
,这样你就不会得到陈旧数据
- use
setState callback
to updatechat
so you won't getstale data
useEffect(() => {
if (connection) {
//...
setChat((ch) => [...ch, newMsg]); // issue with this line. chat is always empty
//...
}
}, [connection]);
哪种方式更合适.
这篇关于反应 useState,useEffect 中的 setState 不更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!