在我的React-Rails应用程序中,我很困惑为什么我无法在componentWillMount中将状态记录到控制台,但可以在componentDidMount中执行此操作。
以下是我的代码:
componentWillMount () {
this.setState({ records: this.props.data });
console.log(this.state.records); // throws TypeError: Cannot read property 'records' of null
}
componentDidMount () {
console.log(this.state.records); // returns records array
}
有什么想法吗?谢谢!
答案 0 :(得分:0)
来自the docs:
setState()
不会立即改变this.state
但会创建一个 待定状态转换。在调用此文件后访问this.state
方法可以返回现有值。
换句话说,在this.state
期间未定义componentWillMount
,使用setState()
不会导致定义componentDidMount
。到达this.state
后,{{1}}将使用您设置的值进行定义。