[英]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.