【发布时间】:2020-04-06 06:42:04
【问题描述】:
在下面的代码 sn-p 中,当我单击更改按钮更改 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)
【问题讨论】:
-
状态改变是异步的,所以你不能在下一行
console.log他们看到他们改变了。在useState行下方尝试 printgisLoading,这样当组件以新状态重新渲染时,它将打印出来 -
这个问题几乎每天都会被问到。请在询问之前搜索 SO。这回答了你的问题了吗? React setState not updating state
-
状态更改是异步的。所以使用开发者工具中的组件标签来监控状态变化。
标签: reactjs react-hooks