React声明周期
React组件的生命周期可以分为挂载,渲染,卸载几个阶段。
- 组件挂载时:
class App extends Component {
static propTypes = {
// ...
};
static defaultProps = {
// ...
};
constructor(props) {
super(props);
this.state = {
// ...
};
}
componentWillMount() {
// ...
}
componentDidMount() {
// ...
}
render() {
return <div>This is a demo.</div>;
}
}
propTypes和defaultProps分别代表props的类型检查和默认类型。这两个属性被声明成静态属性,意味着从类外面也可以访问他们。 例如App.propTypes, App.defaultProps
- 声明周期
componentWillMount
会在render
之前执行,componentDidMount
在render
之后执行。 componentWillMount
componentDidMount
都只在组件初始化时运行一次。
- 组件卸载时
- 组件卸载时只有componentWillUnMount这一个状态,在这里执行一些清理方法,例如事件回收或者清除定时器
- 数据更新过程
class App extends Component {
//组件由父组件更新props而更新的话,会执行这个方法,可以作为React在pros传入后,渲染之前setState的机会,此时调用setState不会二次渲染
componentWillReceiveProps(nextProps) {
// this.setState({})
}
shouldComponentUpdate(nextProps, nextState) {
//接收需要更新的props和state,如果返回false,组件将不再向下执行声明周期方法
// return true;
}
componentWillUpdate(nextProps, nextState) {
// ... 提供需要更新的props和state
}
componentDidUpdate(prevProps, prevState) {
// ... 提供更新前的props和state
}
render() {
return <div>This is a demo.</div>;
}
}
注意: 不要在componentWillUpdate中执行setState,
React声明周期在不同状态下的执行顺序如下:
首次挂载组件:
按顺序执行 getDefaultProps, getInitialState, componentWillMount, render, componentDidMount
卸载组件时:
执行componentWillUnMount
重新挂载组件时:
按顺序执行 getInitialState
, componentWillMount
, render
, componentDidMount
再次渲染组件时,组件接受到更新状态
按顺序执行componentWillReceiveProps
, shouldComponentUpdate
, componentWillUpdate
, render
, componentDidUpdate
注意: 使用ES6 classes
来创建React组件时,static defaultProps = {}
就是调用内部的getDefaultProps
方法,constructor
中的this.state= {}
就是调用getInitialState
方法。
图解React声明周期执行顺序
来源:https://blog.csdn.net/haoyanyu_/article/details/101345986