我想在尚未安装状态时访问state的属性。
class App extends React.Component{ constructor(props){ super(props) this.state = { test: 2, score: test * 2 } }
我想制作score
4但是得到这个错误:
'test' is not defined no-undef
P.Sazxswpoi也不起作用。
你在score: this.state.test
,所以你可以更新你的州没有constructor
,没有后果,像这样:
.setState()
一种方法是在设置状态之前定义变量然后使用它:
constructor(props) {
super(props);
this.state = {
test: 2,
};
this.state.score = this.state.test * 2;
}