如何从州访问未安装的状态

问题描述 投票:0回答:2

我想在尚未安装状态时访问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也不起作用。

javascript reactjs
2个回答
1
投票

你在score: this.state.test,所以你可以更新你的州没有constructor,没有后果,像这样:

.setState()

1
投票

一种方法是在设置状态之前定义变量然后使用它:

constructor(props) {
  super(props);
  this.state = {
    test: 2,
  };
  this.state.score = this.state.test * 2;
}
© www.soinside.com 2019 - 2024. All rights reserved.