DOM 生命周期
在談React的生命周期之前,先來看看原始寫法的生命周期是什么樣的
let app = document.getElementById("app");
// create div
let div = document.createElement("div");
let state = 0;
div.innerHTML = `
<p>${state}</p>
<button>+</button>
<button>die</button>
`;
// mount div
app.appendChild(div);
div.style.border = "1px solid red";
div.querySelector("button").onclick = function() {
state += 1;
// update div
div.querySelector("p").innerText = state;
};
div.querySelectorAll("button")[1].onclick = function() {
// 把所有引用都清除
div.querySelector("button").onclick = null;
div.querySelectorAll("button")[1].onclick = null;
div.remove();
div = null;
// destroy div
};
上面這段代碼描述了一個div的生命周期即創(chuàng)建銷毀過程,如果搞懂了這個那React的生命周期也同理。
React 生命周期圖解

React生命周期圖解
下面可以嘗試著用 React 的生命周期來寫一遍。但是需要注意的是:React 在 16.3版本以后,將一些生命周期方法列為了不安全的生命周期。至于為什么這些生命周期方法是不安全的,React 認(rèn)為這些生命周期方法經(jīng)常被誤解和巧妙地濫用,并且預(yù)計這種濫用可能會在異步渲染方面帶來問題。在 17.0 版本將刪除componentWillMount,componentWillReceiveProps和componentWillUpdate。(從這個版本開始開始,只有新的“UNSAFE_”生命周期名稱起作用。)
componentWillMountcomponentWillReceivePropscomponentWillUpdate
React 生命周期
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
console.log("create");
}
onClick() {
this.setState({
count: this.state.count + 1
});
}
UNSAFE_componentWillMount() {
console.log("will mount");
}
componentDidMount() {
console.log("did mount");
}
UNSAFE_componentWillUpdate() {
console.log("will update");
}
componentDidUpdate() {
console.log("did update");
}
render() {
console.log("mount or update");
return (
<div className="App">
{this.state.count}
<button onClick={() => this.onClick()}>+</button>
</div>
);
}
}
/*console.log依次打印出
create
will mount
mount or update
did mount
will update
mount or update
did update
*/
總結(jié)一下,constructor構(gòu)造函數(shù)是create的作用,組件掛載到DOM上之前會調(diào)用UNSAFE_componentWillMount鉤子,組件掛載調(diào)用render函數(shù),掛載完成調(diào)用componentDidMount鉤子,如果渲染的數(shù)據(jù)發(fā)生更新,也就是操作this.setState()的時候,在更新之前會調(diào)用UNSAFE_componentWillUpdate鉤子,組件更新時再調(diào)用一次render函數(shù),更新完成調(diào)用componentDidUpdate鉤子。