1. componentWillMount()
- 执行场景
- 在
render()之前
- 在
- 解释
- 在
render()之前触发,所以setState不会发生重新渲染(re-render); - 这是服务器端渲染
(server render)中唯一调用的钩子(hook); - 通常情况下推荐使用
constructor()方法替代;
- 在
2. render()
- 执行场景
- 1.在
componentWillMount()方法之后 - 2.在
componentWillReceive(nextProps, nextState)方法之后
- 1.在
3. componentDidMount()
- 执行场景
- 在
render()方法之后
- 在
- 解释
- 1 这个方法可以对DOM进行操作,这个函数之后ref变成实际的DOM;
- 2这里可以加载服务器数据,并且如果使用了redux之类的数据服务,这里可以发加载服务器的action;
- 3这个可以使用
setState()方法触发重新渲染(re-render);
4. componentWillReceiveProps(nextProps)
- 执行环境
- 在已经挂载的组件(mounted component)接收到新的props时触发;
- 简单的说是在除了第一次生命周期(componentWillMount -> render -> componentDidMount)之后的生命周期中出发;
- 解释
- 1如果你需要
props发生变化来更新state,你可能需要比较this.props和nextProps,然后使用this.setState()方法来改变this.state;
- 1如果你需要
- 注意
- 1 React可能会在porps传入时即使没有发生改变的时候也发生重新渲染, 所以如果你想自己处理改变,请确保比较props当前值和下一次值; 这可能造成组件重新渲染;
- 2 如果你只是调用
this.setState()而不是从外部传入props, 那么不会触发componentWillReceiveProps(nextProps)函数;这就意味着:this.setState()方法不会触发componentWillReceiveProps(),props的改变或者props没有改变才会触发这个方法;
5. shouldComponentUpdate(nextProps,nextState)
- 执行场景
- 在接收新的props或state时,或者说在componentWillReceiveProps(nextProps)后触发
- 解释
- 在接收新的props或state时确定是否重新渲染,默认情况返回true,表示会发生重新渲染
- 注意
- 1 这个方法在首次渲染时或者forceUpdate()时不会触发;
- 2 这个方法如果返回false, 那么props或state发生改变的时候会阻止子组件发生重新渲染;
- 3 目前,如果
shouldComponentUpdate(nextProps, nextState)返回false, 那么componentWillUpdate(nextProps, nextState), render(), componentDidUpdate()都不会被触发; - 4
Take care: 在未来,React可能把shouldComponentUpdate()当做一个小提示(hint)而不是一个指令(strict directive),并且它返回false仍然可能触发组件重新渲染(re-render);
- Good Idea
- 在React 15.3以后,
React.PureComponent已经支持使用,个人推荐,它代替了(或者说合并了)pure-render-mixin,实现了shallowCompare()。
- 在React 15.3以后,
6. componentWillUpdate(nextProps, nextState)
- 执行场景
- 在props或state发生改变或者
shouldComponentUpdate(nextProps, nextState)触发后, 在render()之前
- 在props或state发生改变或者
- 解释
- 1 这个方法在组件初始化时不会被调用;
- 注意
- 1 千万不要在这个函数中调用this.setState()方法.;
- 2 如果确实需要响应props的改变,那么你可以在
componentWillReceiveProps(nextProps)中做响应操作; - 3如果
shouldComponentUpdate(nextProps, nextState)返回false,那么componentWillUpdate()不会被触发;
7 componentDidUpdate(prevProps, prevState)
- 执行环境
- 在发生更新或
componentWillUpdate(nextProps, nextState)后
- 在发生更新或
- 解释
- 1该方法不会再组件初始化时触发;
- 2 使用这个方法可以对组件中的DOM进行操作;
- 3 只要你比较了
this.props和nextProps,你想要发出网络请求(nextwork requests)时就可以发出, 当然你也可以不发出网络请求;
- 注意
- 如果
shouldComponentUpdate(nextProps, nextState)返回false, 那么componentDidUpdate(prevProps, prevState)不会被触发;
- 如果
8 componentWillUnmount()
- 执行环境
- 在组件卸载(unmounted)或销毁(destroyed)之前
- 解释
- 这个方法可以让你处理一些必要的清理操作,比如无效的timers、interval,或者取消网络请求,或者清理任何在componentDidMount()中创建的DOM元素(elements);
相关 setState(Object/Function)
- 解释
- 通过事件(event handlers)或服务请求回调(server request callbacks), 触发UI更新(re-render);
- 参数
- 1 可以是Object类型, 这时是异步的setState, 同时接收一个在state发生改变之后的回调, 如this.setState(Object, callback), 其中callback可以是() => { ... this.state ... };
- 2 可以是Function类型, 这时是同步的setState, 例如: (prevState, prevProps) => nextState, 同步存在一定效率问题(不理解), 但是它有一个好处就是支持Immutable;