官网地址:https://zh-hans.reactjs.org/docs/react-component.html#static-getderivedstatefromprops
V17可能会废弃的三个⽣命周期函数⽤getDerivedStateFromProps 替代,⽬前使⽤的话加上UNSAFE_:
componentWillMount componentWillReceiveProps componentWillUpdate
引⼊两个新的⽣命周期函数: static getDerivedStateFromProps getSnapshotBeforeUpdate
/* eslint-disable react/style-prop-object */
import React,{Component} from 'react'
class ComponentName extends Component{
constructor(props){
super(props);
this.state={
counter:0
}
console.log('constructor',this.state.counter);
}
static getDerivedStateFromProps(props, state){
//render调用前,constructor执行后
//初始化挂载及后续更行都会调用
//他应该返回一个对象来更新state,返回null不做任何更新内容
const {counter} = state
console.log('getDerivedStateFromProps', state)
return counter < 8 ? null : {counter: 0};
}
getSnapshotBeforeUpdate(prevProps,prevState){
//在最近⼀次渲染输出(提交到
// DOM 节点)之前调⽤。它使得组件能在发⽣更改之前从 DOM 中
// 捕获⼀些信息(例如,滚动位置)。此⽣命周期的任何返回值将作
// 为参数传递给 componentDidUpdate()。
// 此⽤法并不常⻅,但它可能出现在 UI 处理中,如需要以特殊⽅式
// 处理滚动位置的聊天线程等。
const {counter}=prevState
console.log('getSnapshotBeforeUpdate', counter);
return null
}
componentWillMount(){
//当前组件挂载
console.log('componentWillMount挂载',this.state.counter);
}
componentDidMount(){
//当前组件挂载结束
console.log('componentDidMount',this.state.counter);
}
componentWillUnmount(){//将要废弃
console.log('componentWillUnmount',this.state.counter);
}
componentWillUpdate(){//发生改变前,将要废弃
console.log('componentWillUpdate',this.state.counter);
}
componentDidUpdate(){
//发生改变后
console.log('componentDidUpdate',this.state.counter);
}
shouldComponentUpdate(nextProps,nextState){//改变前判断
const {counter}=this.state;
console.log('shouldComponentUpdate',nextState,this.state.counter);
return counter !== 5;
}
render(){
console.log('render');
const {counter}= this.state
return(
<React.Fragment>
<div>
ComponentName
<h1>{counter}</h1>
<button onClick={this.setcounter}>修改</button>
</div>
{!!(counter % 2) && <Foo />}
</React.Fragment>
)
}
setcounter = ()=>{
this.setState({
counter:this.state.counter+1
})
}
}
class Foo extends Component{
UNSAFE_componentWillReceiveProps(nextProps){//将废弃
console.log('UNSAFE_componentWillReceiveProps');
}
componentWillMount(){
console.log(`卸载组件,componentWillMount`);
}
render(){
return(
<div>
我是Foo组件
<div>Foo counter:{this.props.counter}</div>
</div>
)
}
}
export default ComponentName;