React 生命周期的過程埃元。
image.png
生命周期分為三個階段泥从,分別是:Mounting(掛載階段)、Updating(更新階段)舔腾、Unmounting(卸載階段)溪胶。
一、掛載階段
在掛載階段中稳诚,首先會對組件進(jìn)行掛載哗脖,執(zhí)行
constructor
方法創(chuàng)建組件,然后執(zhí)行render
方法告訴 React 我們的組件中會渲染什么內(nèi)容,之后 React 就會開始將我們要掛載的組件掛載到 DOM 樹上面才避,掛載完畢后 React 會回調(diào)一個生命周期函數(shù)componentDidMount
橱夭,表示已經(jīng)掛載成功。
class App extends Component {
constructor() {
super();
console.log('執(zhí)行 constructor 方法桑逝,', 1);
}
render() {
console.log('執(zhí)行 render 方法棘劣,', 2);
return (
<div>
<h2>Hello React</h2>
</div>
)
}
componentDidMount() {
console.log('執(zhí)行 componentDidMount 方法,', 3);
}
}
image.png
二楞遏、更新階段
在更新階段中茬暇,如果我們在頁面上進(jìn)行數(shù)據(jù)更新修改,調(diào)用
New props
寡喝、setState()
而钞、forceUpdate()
后,React 就會重新調(diào)用render
方法拘荡,生成一個新的 DOM 樹;之后 React 會重新更新這個 DOM 樹撬陵,更新完 DOM 樹后會回調(diào)一個生命周期函數(shù)componentDidUpdate
珊皿,表示已經(jīng)更新成功。
class App extends Component {
constructor() {
super();
this.state = {
num: 0
}
}
render() {
console.log('執(zhí)行 render 方法巨税,', 1);
return (
<div>
<h2>計數(shù):{this.state.num}</h2>
<button onClick={e => this.add()}>+1</button>
</div>
)
}
add() {
this.setState({
num: this.state.num + 1
})
}
componentDidUpdate() {
console.log('執(zhí)行 componentDidMount 方法蟋定,', 2);
}
}
image.png
三、卸載階段
在卸載階段中草添,當(dāng)我們的某個組件從 DOM 樹中移除的時候驶兜,即將移除時會調(diào)用
componentWillUnmount
函數(shù)。
class Cpn extends Component {
render() {
return (
<div>
我是 Cpn 組件
</div>
);
}
componentWillUnmount() {
console.log('執(zhí)行 componentWillUnmount 方法');
}
}
class App extends Component {
constructor() {
super();
this.state = {
isShow: true
}
}
render() {
return (
<div>
<button onClick={e => this.changeShow()}>切換</button>
{this.state.isShow && <Cpn />}
</div>
)
}
changeShow() {
this.setState({
isShow: !this.state.isShow
})
}
}
image.png
四远寸、方法
-
constructor:如果不初始化 state 或不進(jìn)行方法綁定抄淑,則不需要為 React 組件實現(xiàn)構(gòu)造函數(shù)。
通過this.state
賦值對象來初始化內(nèi)部的 state驰后;
為事件綁定實例 (this)肆资; -
componentDidMount:會在組件掛載后(插入DOM 樹中)立即調(diào)用。
依賴于 DOM 的操作可以在這里進(jìn)行灶芝;
在此處發(fā)送網(wǎng)絡(luò)請求(官方建議)郑原;
可以在此處添加定義(會在 componentWillUnmount() 取消訂閱); -
componentDidUpdate:會在更新后被立即調(diào)用夜涕,首次渲染不會執(zhí)行犯犁。
當(dāng)組件更新后,可以在此對 DOM 進(jìn)行操作女器;
可以對更新前后的 props 進(jìn)行網(wǎng)絡(luò)請求酸役,當(dāng) props 未發(fā)生變化時,則不會執(zhí)行網(wǎng)絡(luò)請求; -
componentWillUnmount:會在組件卸載及銷毀之前調(diào)用簇捍。
在此方法中執(zhí)行必要的清理操作只壳;
比如清除 timer ,取消網(wǎng)絡(luò)請求或清除在 componentDidMount() 中創(chuàng)建的訂閱等暑塑;
五吼句、不常用的生命周期
image.png
- getDerivedStateFromProps:state 的值在任何時候都依賴于 props 時使用;該方法返回一個對象來更新 state事格。
- getSnapshotBeforeUpdate:在 React 更新 DOM 之前回調(diào)的一個函數(shù)惕艳,可以獲取 DOM 更新前的一些信息。例如:滾動位置驹愚。
- shouldComponentUpdate(nextProps,nextState):決定是否要重新 render 組件远搪。