在下面的代码片段中,当我单击更改按钮以更改 isLoading
的值时,什么也没发生( isLoading
是假的)。
const App = (props) => {
const [isLoading, setIsLoading] = useState(false)
const buttonHandler = () => {
setIsLoading(current => !current)
console.log(isLoading) // is false
}
return (
<div>
<button onClick={buttonHandler} type="button">
Change
</button>
</div>
)
}
我尝试通过以下方式更改 isLoading 但不影响:
1-setIsLoading(current => !current)
2-setIsLoading(!isLoading)
3-setIsLoading(true)
原文由 user11912021 发布,翻译遵循 CC BY-SA 4.0 许可协议
setIsLoading
是一个异步函数,更新后无法立即获取状态值。来自 React 文档
如果你想获得更新的状态值然后使用
useEffect
挂钩依赖数组。 React 会在每次状态更新后执行这个钩子。