這篇文章將為大家詳細講解有關React中生命周期的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
兩張圖帶你理解 React的生命周期
React的生命周期(舊)

class Life extends React.Component{
// 構造器
constructor(props){
console.log('Life構造器---constructor');
super(props)
this.state={num:0}
}
// 計算+1功能
add=()=>{
const {num} = this.state
this.setState({num:num+1})
}
// 刪除組件
death=()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('text'))
}
force=()=>{
this.forceUpdate()
}
// 將要掛載
componentWillMount(){
console.log('Life將要掛載---componentWillMount');
}
// 已經掛載
componentDidMount(){
console.log('Life已經掛載---componentDidMount');
}
// 刪除觸發
componentWillUnmount(){
console.log('Life刪除觸發---componentWillUnmount');
}
// 是否應該改變數據
shouldComponentUpdate(){
console.log('Life是否改變數據---shouldComponentUpdate');
return true
}
// 將要改變數據
componentWillUpdate(){
console.log('Life將要改變數據---componentWillUpdate');
}
// 改變數據
componentDidUpdate(){
console.log('Life改變數據---componentDidUpdate');
}
render(){
console.log('Life---render');
const {num} = this.state
return(
<div>
<h2>計數器:{num}</h2>
<button onClick={this.add}>點我+1</button>
<button onClick={this.death}>刪除</button>
<button onClick={this.force}>不更改任何狀態的數據,強制更新</button>
</div>
)
}
}
// 渲染頁面
ReactDOM.render(<Life />, document.getElementById('text'))掛載步驟

更新步驟

刪除

總結: 初始化階段: 由ReactDOM.render()觸發—初次渲染1. constructor() ---構造器2. componentWillMount() ---將要掛載3. render() ---render4. componentDidMount() ---掛載時更新階段: 由組件內部this.setSate()或父組件重新render觸發1. shouldComponentUpdate() ---是否要進行更改數據2. componentWillUpdate() ---將要更新數據3. render()4. componentDidUpdate() ---更新數據卸載組件: 由ReactDOM.unmountComponentAtNode()觸發componentWillUnmount() ---卸載
React的生命周期(新)

生命周期的三個階段(新)
初始化階段: 由ReactDOM.render()觸發—初次渲染
1. constructor()
2. getDerivedStateFromProps
3. render()
4. componentDidMount()更新階段: 由組件內部this.setSate()或父組件重新render觸發1. getDerivedStateFromProps
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate
5. componentDidUpdate()卸載組件: 由ReactDOM.unmountComponentAtNode()觸發
1. componentWillUnmount()
重要的勾子
1.render:初始化渲染或更新渲染調用
2.componentDidMount:開啟監聽, 發送ajax請求
3.componentWillUnmount:做一些收尾工作, 如: 清理定時器
即將廢棄的勾子
1.componentWillMount
2.componentWillReceiveProps
3.componentWillUpdate
現在使用會出現警告,下一個大版本需要加上UNSAFE_前綴才能使用,以后可能會被徹底廢棄,不建議使用。
關于“React中生命周期的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。