【问题标题】:React - setState does not update the valueReact - setState 不更新值
【发布时间】:2019-06-14 03:20:17
【问题描述】:

我正在尝试使用 DidMount 中的 localStorage 值更新状态,但它没有更新:

type Props = {
};

type State = {
    id_evaluation: string,
};

class Evaluation extends Component < Props, State > {
    state = {
        id_evaluation: '',
    }

    componentDidMount() {
        const id_eval = getEvaluation();
        console.log('1 - ', id_eval)

        this.setState({
            id_evaluation: '1',
        });

        console.log('2 - ', this.state.id_evaluation)

在第一个 console.log 中我的值为 1,在第二个中它保持为空,它不会更新状态。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    那是因为您在状态更新之前调用了 console.log。试试这个:

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

    看到这个帖子:

    Can I execute a function after setState is finished updating?

    【讨论】:

      【解决方案2】:

      setState 异步工作,因此将console.log 传递为callback 以获取更新状态。

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

      当用作您的代码时,console.log('2 - ', this.state.id_evaluation) 正在打印以前的状态而不是更新的状态。

      【讨论】:

        【解决方案3】:

        this.setState 是一个异步函数。

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

        回调函数可以解决你的问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-19
          • 2018-02-06
          • 2023-04-09
          • 1970-01-01
          • 2020-07-26
          • 2017-12-26
          相关资源
          最近更新 更多