如何访问构造函数中的状态?
对于上下文,在构造函数中使用“ this.state.count”时,收到错误消息:“ TypeError:无法读取未定义的属性” count”。
答案 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};
}