[英]Push into an array useState React
我希望你没事,我想在我的数组中添加一个元素,我该怎么做? 看我的代码:
const [datesState, setDisabledData] = useState([
format(new Date(2021, 4, 1), "dd/MM/yyyy"),
format(new Date(2021, 4, 4), "dd/MM/yyyy")
]);
useEffect(() => {
setDisabledData(oldArray => [...oldArray, format(new Date(2021, 4, 9), "dd/MM/yyyy")]);
}, []);
但它不起作用..
您的代码本身没有问题,但是如果您在 setDisabledData 之后立即放置一个 console.log,那么由于设置 state 是异步的,并且 console.log() 是一个同步 function,console.log 在 setDisabledData 之前完成执行,因此打印旧的 state 信息。
The setState method for class based components has the same problem, but it has a callback function that will be called after state is set, and can be used to wait for state update to finish.
在功能组件中,需要使用 useEffectHook 等待 state 更新。
您可以参考使用钩子时等待 state 更新以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.