Strange behavior of React hooks: delayed data update

前端 未结 3 652
走了就别回头了
走了就别回头了 2020-12-10 18:42

Strange behavior: I expect that the first and the second console.log display a different result, but they display the same result and the value is changed only on the next c

3条回答
  •  不知归路
    2020-12-10 19:00

    The state update is asynchronous so if you are using Hooks you can use useEffect to be notified after an update.

    Here is an example:

    https://codesandbox.io/s/wxy342m6l

    If you are using setState of a React component, you can use the callback

    this.setState((state) => ({count: !state.count}), () => console.log('Updated', this.state.count));

    Remember to use the callback to update state if you need a state value.

提交回复
热议问题