构造函数中的访问状态?

时间:2020-06-30 02:34:42

标签: reactjs

如何访问构造函数中的状态?

对于上下文,在构造函数中使用“ this.state.count”时,收到错误消息:“ TypeError:无法读取未定义的属性” count”。

1 个答案:

答案 0 :(得分:1)

因为您需要首先在构造函数中定义状态。

constructor (props) {
  super(props);
  console.log(this.state.count) // ERROR - state is undefined
}

constructor (props) {
  super(props);
  this.state = {count: 1};
  console.log(this.state.count) // state is defined by this.state = {count: 1};
}