[英]Why is react state(array) empty inside callback function? Why is it not using the updated value from outer scope?
这个问题把我难住了。 我正在尝试将值附加到现有数组,但在 onmessage 回调中,每次调用回调时 state 都是一个空数组! 我无法弄清楚为什么! 任何帮助表示赞赏。
代码片段:
const Example = () => {
const [state, setState] = useState([]);
useEffect(() => {
axios.get("/data").then((resp) => setState(resp.data)); // Array of length of 50
const eventSource = new EventSource("/event");
eventSource.onmessage = (e) => {
console.log(state); // [] - Empty array
const data = JSON.parse(e.data);
setState([data, ...state]); // End result - state is array of length 1
}
return () => eventSource.close();
}, []);
console.log(state); // Array of length 50
// Table rendered with 50 elements
return <Table data={state} />
}
谢谢
设置状态本质上是异步的。 您的 console.log 将始终打印 state 的先前值。 您可以使用 useEffect 在每次更改时获取 state 的更新值 -
useEffect(() => { console.log("value of state is", state)}, [state] // dependancy array//)
尝试使用状态更新器功能。 如果你将一个函数传递给 setState,React 将使用实际状态调用它:
setState(actualState => {
return [data, ...actualState]
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.