學習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.


如果覺得不錯的話,就用點贊來代替五星好評吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章