我是 reactjs 的新手,并尝试制作一个组件。我在 componentWillMount()
中设置了 this.state
,然后我调用了一个方法:
componentWillMount() {
this.setState({ value: this.props.value || "0" });
this.changeCbState = this.changeCbState.bind(this);
this.changeCbState();
}
但是在我的方法中 changeCBState
this.state
是未定义的:
changeCbState() {
console.log(this.state.value)
}
错误:Uncaught TypeError: Cannot read property 'value' of null
最佳答案
问题可能是您不会在构造函数中初始化状态,并且由于 this.setState 是异步的,因此在您尝试访问 changeCbState
之前可能不会初始化状态功能。
还有你在componentWillMount
中编写的初始化代码lifecycle需要进去constructor
自 componentWillMount
方法应该被弃用。
constructor(props) {
super(props);
this.state = {
value: this.props.value || "0"
}
this.changeCbState = this.changeCbState.bind(this);
this.changeCbState();
}
关于javascript - Reactjs 组件 `this.state` 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51836941/