一、新的生命周期函数简介
React 16 版本以后,旧的生命周期函数被弃用,取而代之的是一组新的生命周期函数。主要的区别如下:
命名不同:旧的生命周期函数采用了will和did前缀,如componentWillMount、componentDidUpdate等;而新的生命周期函数则采用了前缀为“unsafe”或没有前缀的命名方式,如UNSAFE_componentWillMount、getDerivedStateFromProps、componentDidUpdate等。
调用时机不同:新的生命周期函数中,许多函数可能会在每次渲染时都被调用,而旧的生命周期函数只会在组件挂载、更新、卸载时调用。
参数不同:新的生命周期函数中,参数有所改变,如getDerivedStateFromProps中会传入props和state两个参数;而旧的生命周期函数中只有一个参数。
副作用不同:新的生命周期函数中,一些函数不允许产生副作用,如UNSAFE_componentWillReceiveProps、shouldComponentUpdate等;而旧的生命周期函数中可以进行DOM操作等产生副作用的操作。
二、为什么弃用一些旧的生命周期函数
React弃用一些旧的生命周期函数是出于以下几个原因:
命名不太符合实际调用。例如,componentWillUpdate和componentDidUpdate是在组件更新之前和之后被调用,但实际上它们同时可以被调用,这可能导致一些误解。
可能会引起副作用。例如,在componentWillReceiveProps进行ajax请求操作可能会阻塞组件的渲染,影响性能。
与异步渲染和Fiber架构结合使用时容易出现问题。新版本的React引入了Fiber架构和异步渲染机制,为了更好地支持这些特性,需要更加细致地控制生命周期函数的调用时机。
因此,React团队决定弃用一些旧的生命周期函数,并推荐开发者使用新的生命周期函数,以更好地适应React未来的发展。
三、案列
<script type="text/babel">
//创建组件
class Sum extends React.Component{
//构造器
constructor(props){
console.log("Sum---constructor");
super(props)
//初始化状态
this.state={sum:0}
}
//加1按钮的回调
add=()=>{
//获取原状态
const {sum}=this.state
//更新状态
this.setState({sum:sum+1})
}
//卸载组件的回调
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
//强制更新的回调
force=()=>{
//调用强制更新的函数
this.forceUpdate()
}
static getDerivedStateFromProps(props,state){
console.log('Sum---getDerivedStateFromProps',props,state);
return null
}
getSnapshotBeforeUpdate(){
console.log("Sum---getSnapshotBeforeUpdate");
//返回快照值 传递给componentDidUpdate
return 'gystt'
}
//组件挂载完毕的生命周期函数
componentDidMount(){
console.log("Sum---componentDidMount");
}
//组件将要卸载时的生命周期函数
componentWillUnmount(){
console.log("Sum---componentWillUnmount");
}
//控制组件更新的“阀门”
shouldComponentUpdate(){
console.log("Sum---shouldComponentUpdate");
return true;
}
//组件更新完毕的生命周期函数
componentDidUpdate(preProps,preState,snapshotValue){
console.log("Sum---componentDidUpdate",preProps,preState);
}
render(){
console.log("Sum---render");
const {sum}=this.state
return(
<div>
<h2>当前求和为:{sum}</h2>
<button onClick={this.add}>点击+1</button>
<button onClick={this.death}>卸载组件</button>
<button onClick={this.force}>强制更新组件</button>
</div>
)
}
}
//渲染组件
ReactDOM.render(<Sum sum={199}/>,document.getElementById('test'))
</script>
注意:尽量避免使用弃用的生命周期函数
个人博客余生的学习笔记