反应状态属性引用自己范围内的属性

时间:2018-11-27 01:43:44

标签: javascript reactjs ecmascript-6

React状态对象中的属性是否可以引用其自身的属性?就像下面的示例一样:

this.state = {
    currentTotal: 30,
    columnLength: Math.ceil(this.currentTotal / 3), // Getting NaN.
}

3 个答案:

答案 0 :(得分:1)

这里的问题是this.currentTotal是未定义的,在此算术期间this.currentTotal / 3会导致NaN。

有几种方法可以解决此问题,但也许最简单的解决方案是在组件Math.ceil(this.currentTotal / 3)完全初始化后才推迟state的计算,如下所示:

class Component {

  constructor() {
  
    const state = {
      currentTotal: 30,
      columnLength: 0
    }
    
    // Defer calculation til after state has been initialised
    state.columnLength = Math.ceil(state.currentTotal / 3)
    
    // Assign your initialised to the component
    this.state = state

    console.log( this.state.columnLength )
  }
  
}

new Component()

答案 1 :(得分:0)

由于您已经需要currentTotal,我认为此解决方案将是最优雅的

constructor() {
  const currentTotal = 30; // initialization
  this.state = {
    currentTotal,
    columnLength: Math.ceil(currentTotal / 3),
  }
}

答案 2 :(得分:-3)

我们通常会执行开关。

this.setState({ isOpen:!this.state.isOpen });

仅使用setState更改状态。