![](/img/trans.png)
[英]why state is not updated after button click in setinterval react?
[英]Why state is not updated after button click using hooks?
你能告訴我為什么 state 沒有更新嗎? 在按鈕單擊時,我更新了 state 但是當我在 setinterval 上控制台我的 state 時它沒有更新,為什么?
這是我的代碼
https://codesandbox.io/s/cool-shamir-8lmpo
<button
onClick={() => {
setState({
filters: {
apps: "DDDDDDH",
searchText: "12333",
taskType: "",
dateFrom: "",
dateTo: "",
status: ""
}
});
}}
>
useEffect(() => {
console.log("===============");
setInterval(() => {
console.log(state);
}, 10000);
}, []);
After button click searchText: "12333",
搜索文本應該是 state 中的12333
,但它顯示為空 wny?
這里發生的情況是,state 在單擊按鈕時會發生變化,但要在控制台中渲染它 setInterval 應該被清除。 嘗試這個..
useEffect(() => {
console.log("===============");
const interval = setInterval(() => {
console.log(state);
}, 10000);
return () => clearInterval(interval);
}, [state]);
在 React 中設置 state 是異步的,而不是使用間隔,您需要跟蹤 state 值useEffect
的依賴數組:
useEffect(() => {
console.log(state);
}, [state]);
為什么在單擊按鈕時更新 state 時使用 setInterval? 嘗試這個。
useEffect(() => {
console.log("===============");
console.log(state);
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.