React16.3.0之前生命周期
創(chuàng)建期:
constructor(props)
componentWillMount()
render()
componentDidMount()
運(yùn)行時(shí):
props發(fā)生變化時(shí)
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)
state發(fā)生變化時(shí)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)
卸載時(shí)
componentWillUnmount()
React16.3.0之后的生命周期
創(chuàng)建期:
constructor(props)
getDerivedStateFromProps(props, state) //靜態(tài)方法 static
render()
componentDidMount()
//或者如下生命周期:
constructor(props)
componentWillMount() / UNSAFE_componentWillMount() //前者會(huì)有警告??
render()
componentDidMount()
getDerivedStateFromProps/getSnapshotBeforeUpdate
和 componentWillMount/componentWillReceiveProps/componentWillUpdate
如果同時(shí)存在眼五,React會(huì)有警告信息,并且只執(zhí)行 getDerivedStateFromProps/getSnapshotBeforeUpdate
【React@16.3.0(以后)】
運(yùn)行時(shí):
props發(fā)生變化時(shí)
getDerivedStateFromProps(props, state) //靜態(tài)方法 static
shouldComponentUpdate(nextProps, nextState, nextContext)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)
// 或者如下生命周期:
componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()//前者會(huì)有警告??
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState, snapshot)
state發(fā)生變化時(shí)
getDerivedStateFromProps(props, status) //靜態(tài)方法 static
shouldComponentUpdate(nextProps, nextState, nextContext)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)
或者如下生命周期:
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate()/UNSAFE_componentWillUpdate()//前者會(huì)有警告??
render()
componentDidUpdate(prevProps, prevState, snapshot)
銷(xiāo)毀時(shí)
componentWillUnmount()
static getDerivedStateFromProps(props, state)
當(dāng)組件的state和props發(fā)生改變的時(shí)候會(huì)在 render() 前會(huì)被執(zhí)行
該方法有兩個(gè)參數(shù)props和state;
class SomeView extends Component {
state = {
count: 20
}
static getDerivedStateFromProps(props, state) {
return {
count: 50
}
}
render() {
return (
<div>{this.state.age}</div>
)
}
}
這個(gè)方法允許組件基于 props 的變更來(lái)更新其內(nèi)部狀態(tài),以這種方式獲得的組件狀態(tài)被稱(chēng)為派生狀態(tài)。應(yīng)該謹(jǐn)慎使用派生狀態(tài)叛拷,可能會(huì)引入潛在的錯(cuò)誤
getSnapshotBeforeUpdate(prevProps, prevState)
在render()的輸出被渲染到DOM之前被調(diào)用呻袭。使組件能夠在它們被更改之前捕獲當(dāng)前值(如滾動(dòng)位置)绘趋。這個(gè)生命周期返回的任何值都將作為第三個(gè)參數(shù)傳遞給componentDidUpdate()