我想知道componentDidUpdate在所有子render方法完成之后,或者在render调用该组件的方法之后,是否执行了React组件的生命周期方法.
由于协调程序以递归方式调用render方法来更新视图,因此我componentDidUpdate会在重新呈现组件的所有子项之后执行预感,但文档中没有足够的信息.什么时候被componentDidUpdate称为?
Li3*_*357 16
该componentDidUpdate方法之后被调用render的组件的方法执行完毕.这意味着它将在所有孩子的render方法完成后被调用.您链接的文档中暗示了这一点:
将此作为在更新组件时对 DOM进行操作的机会.
该组件仅在渲染后更新,因此文档暗示它在所有子节点之后调用,因此父节点已完成重新渲染(尽管有点不清楚).只有在完成更新,子项和所有内容时,您才能真正操作DOM.
例如,假设我们有两个组成部分,A并B与B渲染A组件.componentDidUpdate对于B只会被调用一次B的render结束.在render中B后会完成A的render调用成功,因为孩子们第一次呈现,由于父母是一部分.这意味着您的问题的答案是:componentDidUpdate在所有孩子render完成之后执行.
不知道某个地方是否有更深入的文档,但是确实很容易进行独立测试。
class Nested extends React.Component {
constructor(props){
super(props);
this.state = {foo: undefined};
}
render() {
console.log("Rendered " + this.props.name);
return <div><button onClick={() => {this.setState({foo: Date.now()})}}>Update {this.props.name}</button>{this.props.children ? React.cloneElement(React.Children.only(this.props.children), {foo: this.state.foo}) : undefined}</div>
}
componentDidUpdate() {
console.log("Updated " + this.props.name);
}
}
ReactDOM.render(<Nested name="outer"><Nested name="inner"></Nested></Nested>, document.getElementById("app"));
Run Code Online (Sandbox Code Playgroud)
http://jsbin.com/yiyuhegayo/edit?js,控制台,输出
更新外部组件会导致最内层componentDidUpdate运行,然后是最外层运行。更新内部组件只会导致该组件更新。
有趣的是,render功能相反。首先渲染外部组件,然后渲染内部组件。
| 归档时间: |
|
| 查看次数: |
9220 次 |
| 最近记录: |