React生命周期

React16.3
Reat16.4

  1. 挂载阶段

    • constructor
    • getDerivedStateFromProps(nextProps, prevState)

    Returns an update to a component’s state based on its new props and old state.

    // nextProps: 待更新的props, prevState: 更新前的state(this.state)
    static getDerivedStateFromProps(nextProps, prevState) {
        const {
          location: { pathname }
        } = nextProps;
        const { currentPathname } = prevState;
        if (currentPathname !== pathname) {
          return { ...prevState, currentPathname: pathname };
        }
        return null;
      }
    
    • render
    • componentDidMount

    Called immediately after a component is mounted. Setting state here will trigger re-rendering.

  2. 更新阶段

    • getDerivedStateFromProps(nextProps, prevState) 同上
    • shouldComponentUpdate(nextProps, nextState)

    Called to determine whether the change in props and state should trigger a re-render.
    1.Component always returns true.
    2.PureComponent implements a shallow comparison on props and state and returns true if any props or states have changed.
    3. If false is returned, Component#render, componentWillUpdate and componentDidUpdate will not be called.

    // nextProps:待更新的props, nextState: 待更新的state
    shouldComponentUpdate(nextProps, nextState) {
        if (this.props.name !== nextProps.name) {   //判断name是否改变
          return true;
        }
        if (this.state.age !== nextState.age) {   //判断age是否改变
          return true;
        }
        return false;    //如果两个都不改变,则不重新渲染
      }
    
    • render
    • getSnapshotBeforeUpdate(preProps, preState)

    Runs before React applies the result of render to the document, and returns an object to be given to componentDidUpdate. Useful for saving things such as scroll position before render causes changes to it.

    • componentDidUpdate(preProps, preState, snapshot)

    Called immediately after updating occurs. Not called for the initial render.
    The snapshot is only present if getSnapshotBeforeUpdate is present and returns non-null.

  3. 卸载阶段

    • componentWillUnmount

    Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as cancelled network requests, or cleaning up any DOM elements created in componentDidMount.

react生命周期

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值