函数组件中的React非状态变量不会立即更新



我知道react的useState钩子是异步的,所以如果我使用useState来存储变量并在其上调用set函数,它可能不会立即更新。

然而,现在我使用简单的变量来存储值,但变量值仍然没有更新。我该如何解决同样的问题?

const List=(props)=>{
let count = 1;
const onNextButtonClick = ()=>{
count  = count +1;
console.log(count );
updatePage();
}
return (
//html
)
}

当点击下一个按钮时,我看到c的值没有增加,我在控制台上得到相同的c值。

为什么会发生这种情况?

count需要存储在状态中,因为状态更新可能被分组和异步处理,所以直到下一次渲染时才会看到变化,这是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>