React的生命周期
用一个简单的案列说明:
// index.jsx
/* eslint-disable react/button-has-type */
import React, { Component } from 'react';
import Son from './Son';
export default class index extends Component {
state={
count: 0,
}
componentWillMount() {
console.log('爸爸,componentWillMount');
}
componentDidMount() {
console.log('爸爸,componentDidMount');
}
componentDidUpdate() {
console.log('爸爸,componentDidUpdate');
}
componentWillUnmount() {
console.log('爸爸,componentWillUnmount');
}
componentWillUpdate() {
console.log('爸爸,componentWillUpdate');
}
componentWillReceiveProps() {
console.log('爸爸,componentWillReceiveProps');
}
shouldComponentUpdate(props, nextState) {
const { count } = this.state;
if (count !== nextState.count) {
return true;
}
console.log('爸爸,shouldComponentUpdate');
}
add = () => {
const { count } = this.state;
this.setState({
count: count + 1,
});
}
render() {
console.log('爸爸,render');
const { count } = this.state;
return (
<div>
<button onClick={this.add}>点击</button>
次数:{count}
<Son count={count} />
</div>
);
}
}
import React, { Component } from 'react';
function Grandson({ count }) {
return <div>我是你孙子,我收到了你传递的数字{count}</div>;
}
// Son.jsx
export default class index extends Component {
componentWillMount() {
console.log('儿子,componentWillMount');
}
componentDidMount() {
console.log('儿子,componentDidMount');
}
componentDidUpdate() {
console.log('儿子,componentDidUpdate');
}
componentWillUnmount() {
console.log('儿子,componentWillUnmount');
}
componentWillUpdate() {
console.log('儿子,componentWillUpdate');
}
componentWillReceiveProps() {
console.log('儿子,componentWillReceiveProps');
}
shouldComponentUpdate() {
console.log('儿子,shouldComponentUpdate');
return false;
}
render() {
console.log('儿子,render');
const { count } = this.props;
return (
<div>
我是你儿子
<Grandson count={count} />
</div>
);
}
}
分几种情况:
-
首次渲染,生命周期依次是
-
点击按钮,
UI
变化和依次执行的生命周期是:
-
修改
Son.jsx
中shouldComponentUpdate
,return
为true
后,点击按钮,UI变化和依次执行的生命周期是:
-
注意:如果使用了
shouldComponentUpdate
生命周期,请设置返回值,否则浏览器会报warning
,如果不使用,默认return:true
-
最后用一张完整的图来梳理
react
的整个生命周期
其中getDefaultProps
和getInitialState
是ES5
的写法,这两个生命周期不是获取默认的props
和获取默认的state
,而是设置默认的props
和设置初始state
,现在ES6
的写法由defaultProps
,propTypes
和state
代替