[英]Why state is not updated after button click using hooks?
Could you please tell me why state is not updated?你能告诉我为什么 state 没有更新吗? On button click I updated the state but when I console my state on setinterval it is not updated why?
在按钮单击时,我更新了 state 但是当我在 setinterval 上控制台我的 state 时它没有更新,为什么?
Here is my code这是我的代码
https://codesandbox.io/s/cool-shamir-8lmpo 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",
searchtext should be 12333
in state but it is showing empty wny? After button click searchText: "12333",
搜索文本应该是 state 中的12333
,但它显示为空 wny?
What happens here is, The state is changing when the button gets clicked, but to render it in console setInterval should be cleared.这里发生的情况是,state 在单击按钮时会发生变化,但要在控制台中渲染它 setInterval 应该被清除。 try this..
尝试这个..
useEffect(() => {
console.log("===============");
const interval = setInterval(() => {
console.log(state);
}, 10000);
return () => clearInterval(interval);
}, [state]);
Setting state is async in React, instead of using interval, you need to track the state value useEffect
's dependency array:在 React 中设置 state 是异步的,而不是使用间隔,您需要跟踪 state 值
useEffect
的依赖数组:
useEffect(() => {
console.log(state);
}, [state]);
Why are you using setInterval while you are updating state on button click?为什么在单击按钮时更新 state 时使用 setInterval? Try this.
尝试这个。
useEffect(() => {
console.log("===============");
console.log(state);
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.