为什么我不能在componentWillMount中将状态记录到控制台,但是可以在componentDidMount中?

时间:2016-05-24 15:36:24

标签: ruby-on-rails reactjs

在我的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
}

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

来自the docs

  

setState()不会立即改变this.state但会创建一个   待定状态转换。在调用此文件后访问this.state   方法可以返回现有值。

换句话说,在this.state期间未定义componentWillMount,使用setState()不会导致定义componentDidMount。到达this.state后,{{1}}将使用您设置的值进行定义。