在componentWillMount中调用setState之后,在render中保证状态

时间:2017-11-01 12:12:51

标签: javascript reactjs

如果我在setState中呼叫componentWillMount,则render方法中保证存在状态吗?注意我没有在回调中调用setState。

Facebook声明:“在render()之前调用componentWillMount,因此在此方法中同步调用setState()不会触发额外的渲染。”

引用“不触发额外渲染”对我来说意味着this.state将是componentWillMount中设置的内容,但我不完全清楚是否是这种情况。有人可以更轻松吗? (由于setState是异步操作,我不确定我是否引入了竞争条件,或者在setStatecomponentWillMount之后是否保证了渲染生命周期方法

例如:

class Blah extends Component {
    componentWillMount() {
        this.setState({ someState })
    }
    render() {
        // this.state.someState <--- guaranteed to be the value I set in componentWillMount?
    }
}

1 个答案:

答案 0 :(得分:0)

是的,没有React文档中所述的额外呈现:

在安装发生之前立即调用

componentWillMount()。它在render()之前调用,因此在此方法中同步调用setState()不会触发额外的渲染。

参考:https://reactjs.org/docs/react-component.html#componentwillmount

相关问题