React生命周期

2021-05-14  本文已影响0人  三粒黑子球

React16.3.0之前生命周期

创建期:

constructor(props)
componentWillMount()
render()
componentDidMount()

运行时:

props发生变化时
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)
state发生变化时
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)

卸载时

componentWillUnmount()

React16.3.0之后的生命周期

创建期:

constructor(props)
getDerivedStateFromProps(props, state) //静态方法 static
render()
componentDidMount()
//或者如下生命周期:

constructor(props)
componentWillMount() / UNSAFE_componentWillMount() //前者会有警告⚠️
render()
componentDidMount()

getDerivedStateFromProps/getSnapshotBeforeUpdatecomponentWillMount/componentWillReceiveProps/componentWillUpdate如果同时存在,React会有警告信息,并且只执行 getDerivedStateFromProps/getSnapshotBeforeUpdate【React@16.3.0(以后)】

运行时:

props发生变化时
getDerivedStateFromProps(props, state) //静态方法 static
shouldComponentUpdate(nextProps, nextState, nextContext)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)

// 或者如下生命周期:

componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()//前者会有警告⚠️
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState, snapshot)
state发生变化时
getDerivedStateFromProps(props, status) //静态方法 static
shouldComponentUpdate(nextProps, nextState, nextContext)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)
或者如下生命周期:

shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate()/UNSAFE_componentWillUpdate()//前者会有警告⚠️
render()
componentDidUpdate(prevProps, prevState, snapshot)

销毁时

componentWillUnmount()
图示生命周期

static getDerivedStateFromProps(props, state)

当组件的state和props发生改变的时候会在 render() 前会被执行

该方法有两个参数props和state;

class SomeView extends Component {
    state = {
        count: 20
    }
    static getDerivedStateFromProps(props, state) {
        return {
            count: 50
        }
    }
    render() {
        return (
            <div>{this.state.age}</div>
        )
    }
}

这个方法允许组件基于 props 的变更来更新其内部状态,以这种方式获得的组件状态被称为派生状态。应该谨慎使用派生状态,可能会引入潜在的错误

getSnapshotBeforeUpdate(prevProps, prevState)

在render()的输出被渲染到DOM之前被调用。使组件能够在它们被更改之前捕获当前值(如滚动位置)。这个生命周期返回的任何值都将作为第三个参数传递给componentDidUpdate()

父组件子组件初始化示意图(网图) 父组件发生改变示意图(网图) 卸载组件示意图(网图)
上一篇 下一篇

猜你喜欢

热点阅读