我想在尚未安装状态时访问状态的属性。
class App extends React.Component{ constructor(props){ super(props) this.state = { test: 2, score: test * 2 } }
我想打score
4,但出现此错误:
未定义“测试”
P.S score: this.state.test
也不起作用。
答案 0 :(得分:1)
您在constructor
中,因此可以在没有.setState()
且没有任何后果的情况下更新状态,例如:
constructor(props) {
super(props);
this.state = {
test: 2,
};
this.state.score = this.state.test * 2;
}
答案 1 :(得分:1)
一种实现方法是在设置状态之前定义变量,然后使用它:
constructor(props) {
super(props);
const test = 2;
this.state = {
test,
score: test * 2
};
}