Javascript React状态属性引用自己范围内的属性
React state对象中的属性是否有方法引用其自身的属性?如以下示例所示:Javascript React状态属性引用自己范围内的属性,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,React state对象中的属性是否有方法引用其自身的属性?如以下示例所示: this.state = { currentTotal: 30, columnLength: Math.ceil(this.currentTotal / 3), // Getting NaN. } 我们通常做的是实现切换 this.setState({ isOpen:!this.state.isOpen }); 仅使用setState更改状态。这里的问题是this.currentTotal未定义,
this.state = {
currentTotal: 30,
columnLength: Math.ceil(this.currentTotal / 3), // Getting NaN.
}
我们通常做的是实现切换
this.setState({ isOpen:!this.state.isOpen });
仅使用setState更改状态。这里的问题是
this.currentTotal
未定义,这将在该算法期间导致NaN:this.currentTotal/3
有几种方法可以解决此问题,但最简单的解决方案可能是将Math.ceil(this.currentTotal/3)
计算推迟到组件状态
完全初始化后,如下所示:
类组件{
构造函数(){
常量状态={
总数:30,
列长度:0
}
//将计算推迟到状态初始化后
state.columnLength=Math.ceil(state.currentTotal/3)
//将您的初始设置分配给组件
this.state=状态
console.log(this.state.columnLength)
}
}
new Component()
既然您已经需要currentTotal,我认为这个解决方案将是最优雅的
constructor() {
const currentTotal = 30; // initialization
this.state = {
currentTotal,
columnLength: Math.ceil(currentTotal / 3),
}
}
在React中,
状态
和道具
是不可变的。组件的状态
可以在组件的构造函数中进行变异。请注意,此常量状态。columnLength
无效。尝试删除常量
@JayHarris好的定位-谢谢!将set state与回调函数一起使用我很确定这段代码没有运行耶,{}
丢失了另外注意:不完全是,顾名思义-currentTotal值可能会更改。@Abbadiah如果它可以更改,就没有必要将它放在构造函数中,不是吗?OP最终需要使用setStates
。此外,所选答案与我的答案做的事情相同,只是需要更多的代码行