setState doesn't update the state immediately

前端 未结 12 2522
暖寄归人
暖寄归人 2020-11-21 05:25

I would like to ask why my state is not changing when I do an onclick event. I\'ve search a while ago that I need to bind the onclick function in constructor but still the s

12条回答
  •  情深已故
    2020-11-21 05:52

    Your state needs some time to mutate, and since console.log(this.state.boardAddModalShow) executes before the state mutates, you get the previous value as output. So you need to write the console in the callback to the setState function

    openAddBoardModal() {
      this.setState({ boardAddModalShow: true }, function () {
        console.log(this.state.boardAddModalShow);
      });
    }
    

    setState is asynchronous. It means you can’t call it on one line and assume the state has changed on the next.

    According to React docs

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

    Why would they make setState async

    This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.

    Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

提交回复
热议问题