在下面的代码片段中,当我单击“更改”按钮更改 的值时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>
)
}
Run Code Online (Sandbox Code Playgroud)
我尝试通过以下方式更改 isLoading 但不影响:
1-setIsLoading(current => !current)
2-setIsLoading(!isLoading)
3-setIsLoading(true)
Run Code Online (Sandbox Code Playgroud)
setIsLoading 是一个异步函数,更新后无法立即获取状态值。
setState操作是异步的,并且被批处理以提高性能。setState() 不会立即改变它。因此 setState 调用是异步的,并且是批处理的,以获得更好的 UI 体验和性能。这适用于两个
functional/Class组件。
来自 React 文档
React 可以将多个 setState() 调用批处理为单个更新以提高性能。因为 this.props 和 this.state 可能会异步更新,所以你不应该依赖它们的值来计算下一个状态。你可以在这里阅读更多关于这个
如果要获取更新的状态值,请使用useEffect带有依赖项数组的钩子。React 会在每次状态更新后执行这个钩子。
const {useEffect, useState } = React;
const App = (props) => {
const [isLoading, setIsLoading] = useState(false)
const buttonHandler = () => {
setIsLoading(current => !current)
}
useEffect( () => {
console.log(isLoading);
}, [isLoading]);
return (
<div>
<button onClick={buttonHandler} type="button">
Change
</button>
{isLoading? "Loading...": null}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));Run Code Online (Sandbox Code Playgroud)
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root">
loading.....
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17628 次 |
| 最近记录: |