当状态尚未挂载时,我想访问状态的属性。App类扩展了React.Component { 构造函数(道具){ 超级(道具) this.state = { 测试:2 得分:测试* 2 }}我想输入score4,但出现此错误:未定义“测试”PSscore: this.state.test也不起作用。
2 回答

阿波罗的战车
TA贡献1862条经验 获得超6个赞
您处于constructor,因此您可以更新状态,.setState()而不会产生任何后果,例如:
constructor(props) {
super(props);
this.state = {
test: 2,
};
this.state.score = this.state.test * 2;
}

倚天杖
TA贡献1828条经验 获得超3个赞
一种方法是在设置状态之前定义变量,然后使用它:
constructor(props) {
super(props);
const test = 2;
this.state = {
test,
score: test * 2
};
}
添加回答
举报
0/150
提交
取消