数据更新
更新过程:父组件向下传递 props 或组件自身执行 setState 方法时发生的一系列更新动作
更新过程的生命周期:
import React, { Component, PropTypes } from 'react';
class App extends Component {
componentWillReceiveProps(nextProps) {
// this.setState({})
}
shouldComponentUpdate(nextProps, nextState) {
// return true;
}
componentWillUpdate(nextProps, nextState) {
// ...
}
componentDidUpdate(prevProps, prevState) {
// ...
}
render() {
return <div>This is a demo.</div>;
}
}
若组件自身的 state 更新了,那么会依次执行 shouldComponentUpdate 、 componentWillUpdate 、render 和 componentDidUpdate
- shouldComponentUpdate 是一个特别的方法,它接收需要更新的 props 和
state,让开发者增加必要的条件判断,让其在需要时更新,不需要时不更新 - shouldComponentUpdate 的本质是用来进行正确的组件渲染。
假设以后如下图的组件关系:
当父节点 props 改变的时候,在理想情况下,只需渲染在一条链路上有相关 props 改变的节点即可
例如:
注意:无状态组件是没有生命周期方法的,这也意味着它没有 shouldComponent-Update。渲染到该类组件时,每次都会重新渲染。
为了更放心地使用,引用 Recompose 库的 pure 方法:
const OptimizedComponent =pure(ExpensiveComponent);
- componentWillUpdate 和 componentDidUpdate 这两个生命周期方法很容易理解,对应的初始化方法也很容易知道,它们代表在更新过程中渲染前后的时刻
组件是由父组件更新 props 而更新的,那么在 shouldComponentUpdate 之前会先执行componentWillReceiveProps 方法。此方法可以作为 React 在 props 传入后,渲染之前 setState 的机会
注意:不能在 componentWillUpdate 中执行 setState
说明:
- Tabs组件的activeIndex prop 只由外组件来更新
componentWillReceiveProps(nextProps) {
if ('activeIndex' in nextProps) {
this.setState({
activeIndex: nextProps.activeIndex,
});
}
}
传入的props判断是否存在activeIndex。如果用了activeIndex初始化组件,那么每次组件更新前都会去更新组件内部的activeIndex state,达到更新组件的目的
- tab 点击事件
handleTabClick(activeIndex) {
const prevIndex = this.state.activeIndex;
if (this.state.activeIndex !== activeIndex && 'defaultActiveIndex' in this.props) {
this.setState({
activeIndex,
prevIndex,
});
this.props.onChange({ activeIndex, prevIndex });
}
}
整体流程
生命周期方法之间关系,及关键 API 调用反馈