[英]React non state variables inside function component are not updated instantly
I know that useState hook of react is asynchronous so if I use useState to store variable and call set function on it, it may not be updated instantly.我知道 React 的 useState 钩子是异步的,所以如果我使用 useState 来存储变量并在其上调用 set 函数,它可能不会立即更新。
However now I am using simple variables to store the value, but still the variable value is not updated.但是现在我使用简单的变量来存储值,但变量值仍然没有更新。 How can I resolve the same?
我该如何解决?
const List=(props)=>{
let count = 1;
const onNextButtonClick = ()=>{
count = count +1;
console.log(count );
updatePage();
}
return (
//html
)
}
I see that the value of c is not getting incremented whenever the next button is clicked and I am getting the same value of c on console.我看到每当单击下一个按钮时 c 的值都没有增加,并且我在控制台上获得了相同的 c 值。
Why is this happening?为什么会这样?
count
needs to be stored in state and, because state updates may be grouped and processed asynchronously, you won't see the change until the next render which is where useEffect
comes in useful. count
需要存储在 state 中,并且因为 state 更新可能会被分组和异步处理,所以在下一次渲染之前你不会看到变化,这就是useEffect
有用的地方。
const { useEffect, useState } = React; function Example() { const [ count, setCount ] = useState(0); function onNextButtonClick() { setCount(count + 1); // the other thing } useEffect(() => { if (count) console.log(count); }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={onNextButtonClick}> Click me </button> </div> ); }; // Render it ReactDOM.render( <Example />, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.