完整生命週期
constructor(props) // 初始化參數
componentWillMount()
render() // 第一次渲染
componentDidMount()
當父組件向子組件傳入props發生改變後,依次調用
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate()
render() //子組件更新渲染
componentDidUpdate()
當組件自身state發生變化後
componentWillUpdate()
render() //組件再次更新渲染
componentDidUpdate()
當組件卸載
componentWillUnmount()
生命週期詳解
componentDidMount() 此處請求接口數據
componentWillReceiveProps(nextProps) 子組件得到新props時觸發,做用是在子組件再次渲染前,更新子組件自身的state,以後會觸發shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState) 接受的props發生變化或者自身state變化都會觸發該生命週期,在今生命週期能夠作一些渲染的優化,默認返回true,就是默認須要更新組件,從新渲染,nextProps nextState 都是新state 新props,this.props this.state 表示舊的props state,根據需求作優化,好比在某些狀況下返回false,便再也不進行組件更新了,提高頁面性能
static getDerivedStateFormProps(nextProps, prevState)
替代 componentWillReceiveProps 返回的結果會送給setState 若是什麼都不改變就返回null
static 聲明靜態函數,沒法訪問this,也就是一個純函數,輸出徹底由輸入決定
除了shouldComponentUpdate以外,render前的全部生命週期都被替代
返回新的state,從新進行setSate後,react會去控制再也不進行新的更新
AJAX請求在依舊在componentDidMount 中進行,只有在一些特定狀況下實用 (此處還未深刻了解
貌似用的場景不多
eg:
static getDerivedStateFromProps(nextProps, prevState) {
console.log(nextProps); // 新傳入的props
console.log(prevState); // 舊的state
//console.log(this.props);
return {
value: nextProps.value
}
}
例子
這個例子讓你更好的理解幾個生命週期的做用
Github地址在這裏
參考react官方文檔
State & 生命週期 &&
性能優化 章節