【问题标题】:How to access unmounted state from state如何从状态访问卸载状态
【发布时间】:2019-09-15 00:24:18
【问题描述】:

我想在 state 尚未挂载时访问 state 的属性。

类 App 扩展 React.Component{
    构造函数(道具){
    超级(道具)
    这个.state = {
       测试:2,
       分数:测试 * 2
    }
}

我想让score 4 但得到这个错误:

'test' 未定义 no-undef

P.S score: this.state.test 也不起作用。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    一种方法是在设置状态之前定义变量然后使用它:

    constructor(props) {
      super(props);
      const test = 2;
      this.state = {
        test,
        score: test * 2
      };
    }
    

    【讨论】:

      【解决方案2】:

      您在constructor 中,因此您可以在没有.setState() 的情况下更新您的状态,并且不会产生任何后果,就像这样:

      constructor(props) {
        super(props);
        this.state = {
          test: 2,
        };
        this.state.score = this.state.test * 2;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-12
        • 2015-11-28
        • 1970-01-01
        • 2023-03-23
        • 2017-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        相关资源
        最近更新 更多