学习React(21) - Updating 生命周期方法介绍

  1. static getDerivedStateFromProps(props, state), 这个方法is called every time a component is re-rendered.
    这个方法返回either null or an object that represents the updated state of the component.
    This method is used when the state depends on the props of the component.
    在这个方法里,你不能cause any side effects and get the odd state from props, 比如说HTTP requests.

  2. shouldComponentUpdate(nextProps, nextState).
    This method receives the updated props and state and the purpose of this method is clear from its name.
    It dictates if the component should re-render or not.
    By default, all classes components will re-render whenever the props they receive or their state changes.
    This method can prevent that default behavior by returning false.
    This method is basically for performance optimization.
    Do not cause side effects. Ex: HTTP requests Calling the setState method.

  3. render()
    Only required method.
    Read props & state and return JSX.
    Do not change state or internet with DOM or make ajax calls.

  4. getSnapsshotBeforeUpdate(prevProps, prevState)
    This method is called right before the changes from the virtual DOM are to be reflected in the DOM.
    Using this method to capture some information from the DOM. For example, you can read the user’s scroll position and after the update maintain that scroll position by performing some calculations.
    Method will either return null or return a value. Returned value will be passed as the third parameter to the next method.

  5. componentDidUpdate(prevProps, prevState, snapshot)
    This method is called after the render is finished in the re-render cycles. This means you can be sure that the component and all its sub components have properly rendered itself after the update.
    This method is guaranteed to be called only once in each re-render cycle.
    This cause side effects. That is you can make ajax calls. But before making the call you need to compare the prevProps with new props and then decide whether to make the ajax call or not. If you are not comparing, you are making unwanted requests which is not really a good idea.
    This method is called once after the component has rear-ended and they suitable to make ajax calls based on the previous and current props value.


讲了这么多,现在就用代码来演示一下吧:
还是用上一篇博文所用的文件:Lifecycle.js 和 LifecycleChild.js

// Lifecycle.js 文件
import React, { Component } from 'react'
import LifecycleB from './LifecycleChild'

class Lifecycle extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             name: "World"
        }
        console.log("LifecycleA constructor")
    }
    
    static getDerivedStateFromProps(props, state) {
        console.log("LifecycleA getDerivedStateFromProps")
        return null;
    }

    componentDidMount() {
        console.log("LifecycleA componentDidMount")
    }

    shouldComponentUpdate() {
        console.log("LifecycleA shouldComponentUpdate")
        return true
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log("LifecycleA getSnapshotBeforeUpdate")
        return null
    }

    componentDidUpdate() {
        console.log("LifecycleA componentDidUpdate")
    }

    changeState = () => {
        this.setState({
            name: 'Codevolution'
        })
    }

    render() {
        console.log("LifecycleA render")
        return (
            <div>
                Lifecycle A
                <button onClick={this.changeState}>Change state</button>
                <LifecycleB/>
            </div>
        )
    }
}

export default Lifecycle
// LifecycleChild.js 文件
import React, { Component } from 'react'

class LifecycleChild extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             name: "World"
        }
        console.log("LifecycleB constructor")
    }
    
    static getDerivedStateFromProps(props, state) {
        console.log("LifecycleB getDerivedStateFromProps")
        return null;
    }

    componentDidMount() {
        console.log("LifecycleB componentDidMount")
    }

    shouldComponentUpdate() {
        console.log("LifecycleB shouldComponentUpdate")
        return true
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log("LifecycleB getSnapshotBeforeUpdate")
        return null
    }

    componentDidUpdate() {
        console.log("LifecycleB componentDidUpdate")
    }

    render() {
        console.log("LifecycleB render")
        return (
            <div>
                Lifecycle B
            </div>
        )
    }
}

export default LifecycleChild

App.js 文件:

// App.js 文件
import React from 'react';
import './App.css';
import Lifecycle from './Lifecycle'

function App() {
  return (
    <div className="App">
      <Lifecycle/>
    </div>
  );
}

export default App;

结果如下:
在这里插入图片描述
当点击了按钮Change state之后,在chrome 里的console就会显示这个:
在这里插入图片描述


介绍
Unmounting Phase Method:
这个方法只有一个:componentWillUnmount().
这个方法Method is invoked immediately before a component is unmounted and destroyed.
In this method, you can perform some cleanup tasks like cancelling any network requests, removing event handlers, cancelling any subscriptions and also invalidating timers from set timeout or set interval.
What you shouldn’t do is called the setState method that is simply because the component is never remembered after it has been unmounted.
This method performs necessary cleanup and don’t call setState.


介绍
Error Handling Phase Method:
这个一共有两个方法:static getDerivedStateFromError(error) 和 componentDidCatch(error, info).
These two methods are called when there is an error either during rendering, in a lifecycle method, or in the constructor of any child component.


如果觉得不错的话,就用点赞来代替五星好评吧!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值