React - setState does not update the value

后端 未结 3 1093
深忆病人
深忆病人 2021-01-28 16:49

I am trying to update the state with a localStorage value in DidMount, but it is not updating:

type Props = {
};

type State = {
    id_evaluation: string,
};

c         


        
相关标签:
3条回答
  • 2021-01-28 17:27

    setState works asynchronously so pass console.log as callback to get updated state.

    this.setState({ id_evaluation: '1'}, () => console.log('2- ', this.state.id_evaluation));
    

    when used as your code, console.log('2 - ', this.state.id_evaluation) is printing previous state not the updated state.

    0 讨论(0)
  • 2021-01-28 17:28

    this.setState is an async function.

     this.setState({
            id_evaluation: '1',
     }, () => console.log('2 - ', this.state.id_evaluation));
    

    Callback function would solve your problem.

    0 讨论(0)
  • 2021-01-28 17:33

    That is because you call console.log before the state has updated. Try this:

    this.setState({
      id_evaluation: '1',
    }, () => {
      console.log('2 - ', this.state.id_evaluation);
    });
    

    See this thread:

    Can I execute a function after setState is finished updating?

    0 讨论(0)
提交回复
热议问题