react生命周期,先上官网的图
关于各生命周期函数的参数、返回值以及何时执行,啥也不说了,上代码,自己跑一边就啥都明白了。
//组件
class Testlifecycles extends React.Component {
constructor(props) {
super(props);
console.log('constructor');
this.handleClick = this.handleClick.bind(this);
this.state = {b: 1};
// getDefaultProps:接收初始props
// getInitialState:初始化state
}
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps', props, state);
// 组件每次被rerender的时候,包括在组件构建之后(虚拟dom之后,实际dom挂载之前),每次获取新的props或state之后;;每次接收新的props之后都会返回一个对象作为新的state,返回null则说明不需要更新state
return state;
}
componentDidCatch(error, info) {
console.log('componentDidCatch', error, info);
// 获取到javascript错误
}
handleClick() {
this.props.parentClick();
}
render() {
return <h2 onClick={this.handleClick}>点击试一下,a:{this.props.a}</h2>;
}
componentDidMount() {
console.log('componentDidMount');
// 挂载后
}
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate', nextProps, nextState);
// 组件Props或者state改变时触发,true:更新,false:不更新
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('getSnapshotBeforeUpdate', prevProps, prevState);
// 组件更新前触发
return null;
}
componentDidUpdate() {
console.log('componentDidUpdate');
// 组件更新后触发
}
componentWillUnmount() {
console.log('componentWillUnmount');
// 组件卸载时触发
}
}
//在App中调用Testlifecycles组件
class App extends React.Component {
constructor(props) {
super(props);
this.state = {a: 1};
}
parentClick() {
this.setState({a: 2});
}
render() {
let x;
if (this.state.a === 1) {
x = (
<Testlifecycles
parentClick={() => this.parentClick()}
a={this.state.a}
/>
);
} else {
x = <div>estlifecycles组件被卸载</div>;
}
return <div>{x}</div>;
}
}
//将App挂载到根节点下
ReactDOM.render(<App />, document.getElementById('root'));