首页 文章

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

提问于
浏览
3

如果我在 componentWillMount 中调用 setState ,是否保证 render 方法中存在状态?注意我不是在回调中调用setState .

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

引用"Not triggering an extra render"对我来说意味着 this.state 将是 componentWillMount 中设定的,但我不完全清楚是否是这种情况 . 有人可以更轻松吗? (由于 setState 是一个异步操作,我引入了竞争条件,或者如果在 componentWillMount 之后的 setState 中保证了渲染生命周期方法)

例如:

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

1 回答

  • 0

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

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

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

相关问题