反应中具有布尔值的useState

新手上路,请多包涵

在下面的代码片段中,当我单击更改按钮以更改 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 许可协议

阅读 680
1 个回答

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'));
 <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>

原文由 Sohail Ashraf 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进