React组件生命周期
Mounting:组件被挂载(页面上被创建)
Updating:组件被重新渲染(页面上被更新)
Unmounting:组件被卸载(页面上被移除)
componentWillMount() 在渲染前调用,在客户端也在服务器。
componentDidMount() 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。如果你想和其他的JavaScript框架一起使用,可以在这个方法中调用setTimeout,setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI).
componentWillReceiveProps() 在组件接收到一个新的prop时被调用,这个方法在初始化render时不会被调用。
shouldComponentUpdate() 返回一个布尔值,在组件接收到新的props或者state时被调用。在初始化时使用forceUpdate时不被调用。可以在你确认不需要更新组件时使用。返回true则更新,会执行componentWillUpdate()和componentDidUpdate();如果返回false则不更新。默认返回true。
componentWillUpdate() 在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
componentDidUpdate() 在组件完成更新后立即调用。在初始化时不会被调用。
componentWillUnmount() 在组件从DOM中移除的时候立刻被调用。

执行顺序:
Mounting挂载(只执行一次)
当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
- constructor()
- componentWillMount()
- render()
- componentDidMount()
render() 方法是 class 组件中唯一必须实现的方法,其他方法可以根据自己的需要来实现。
Updating更新(可以执行多次)
每当组件的 state 或 props 发生变化时,组件就会更新。
当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
- componentWillReceiveProps()
- shouldComponentUpdate()
- componentWillUpdate()
- render()
- componentDidUpdate()
Unmounting卸载
当组件从 DOM 中移除时会调用如下方法:
- componentWillUnmount()
1807

被折叠的 条评论
为什么被折叠?



