学完旧的生命周期,自然接下来学现有的生命周期
卸载(Unmount)
和旧生命周期一致,且就一个方法,这里就不写示例了,参考博客12即可
挂载(Mount)
import React from 'react';
import ReactDOM from 'react-dom';
class LifeDemo extends React.Component {
//弃用constructor,故不做contructor示例
state = {cnt: 0}
static getDerivedStateFromProps(props, state) {
console.log(`getDerivedStateFromProps,state:${state.cnt}`);
if (props.cnt === undefined) {
return null;
} else {
return {cnt:props.cnt};
}
}
componentDidMount() {
console.log(`componentDidMount,state:${this.state.cnt}`);
}
add = () => {
this.setState({cnt: this.state.cnt + 1})
}
render() {
return (
<div>
<h3>演示加载</h3>
<p>{this.state.cnt}</p>
<button onClick={this.add}>点我加一</button>
</div>
)
}
}
ReactDOM.render(<LifeDemo/>, document.getElementById("demo"));
ReactDOM.render(<LifeDemo cnt={10}/>, document.getElementById("demo1"));
getDerivedStateFromProps简单说明一下:
- 该钩子很少用,能不用就别用,官网说的
- 入参是props和state,该方法创建的意义是根据props修改state,和setState类似,返回object就是state
- 必须有返回,null就是不修改state,但不能是undefined
- 返回非null时,state就不可再进行setState操作了
更新(Update)
class LifeDemo extends React.Component {
state = {cnt: 0, inputValue: null}
static getDerivedStateFromProps(props, state) {
console.log("getDerivedStateFromProps");
return null;
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log("shouldComponentUpdate");
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("getSnapshotBeforeUpdate");
return 'snapshot';
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log(`componentDidUpdate,接收getSnapshotBeforeUpdate返回值:${snapshot}`);
this.input1.value = null;
}
add = () => {
this.setState({cnt: this.state.cnt + 1});
this.setState({inputValue: this.input1.value});
}
render() {
return (
<div>
<h3>演示更新</h3>
<p>{this.state.cnt},用户输入了:{this.state.inputValue}</p>
<button onClick={this.add}>点我加一</button>
<input type="text" ref={c => this.input1 = c}/>
</div>
)
}
}
getSnapshotBeforeUpdate直译就是在更新之前获取快照,就是将上一次更新的数据进行保存,主要用于滚动条,这里只做上面这个简单示例
总结两句:
- 就有的三个will是弃用,并非是加上UNSAFE_就可以
- 新增的两个钩子函数使用场景很少,而且能不用就尽量别用
- 没定义这些钩子函数,react也是按照生命周期的顺序进行执行的,在父类里已经定义了,其实你可以理解为python里的装饰器,父类里这些方法的动作还是会继续做的,不会受你是否定义的影响