Gitbub github.com/15997111963…

The followingUNSAFE_The first cycles are the ones that are officially going to be scrapped

keepUNSAFE_Prefix can also continue to use the latest 16.11.0 will throw a warning in the large version of the 17.0 thoroughly remove componentWillMount, componentWillUpdate, componentWillReceiveProps these three life cycle Help to understand but do not recommend further use and study

When components are mounted

constructor()

  • classThe constructor inherits from the parent classComponentYou can do some basic binding
  • Can be boundrefReact.createdref (), bind to the eventthisorstateAccording to thepropsGet default data, etc
  • Only trigger once!!

static getDerivedStateFromProps(props, state)

  • The new static period is used insteadcomponentWillReceiveProps
  • Only re-render in the parent componentpropsThe state update will trigger this cycle as well. Frankly, it has been very difficult to use for a long time. Don’t be misled by what I wrote earlier.
  • this.setState()Not triggergetDerivedStateFromProps
  • If you want to trigger the needthis.forceUpdate(callback)=> {fact: Sometimes some variables are stored inside components without having to display them in the view layerthisWhen we change this value under certain conditions, it does not trigger rerenderingthis.forceUpdate()Manual trigger tellingreactI want to render render me!! Also remember that doing so will skip this component directlyshouldComponentUpdate()Render directly so try to avoid doing this}
  • It is not accessible within this cyclethis

A lot of people who just see this cycle may not quite understand We can according to the current in componentWillReceiveProps props and the change of the next props for enclosing setState or derived data such as practice In this cycle We are unable to compare So what do we do

In my opinion, the purpose of this cycle is to derive data better. In many cases, the data we need is derived from props, and we cannot use props directly. In this case, we can use this cycle to store the derived data in state for use Rather than frequent trigger componentWillReceiveProps continuously render ()

static getDerivedStateFromProps(props, state) {
    if (state.data.length === 0 && props.data.length) {
        return { data: props.data }
    }
    return null
}
Copy the code

If you need to update the state, you don’t need to return null. If you need to do a simple comparison between props and the previous state, the object of the return will update the state

If we just want to updatestateIn thedataBut don’t update the others we don’t need likereduxIn the samereturn {... state, data}We just need to update the one we want to update

For most of The Times mentioned above, we need to use componentDidUpdate or even shouldComponentUpdate(should consider the name and the validity of the cycle) to perform some operations or update based on the current props and the next one We try to avoid this pose.)

UNSAFE_componentWillMount()

  • In this cyclerenderSome people like to do some subscription or listening operations here suggest moving toconstructororcomponentDidMountIn the

render()

  • Update componentpropsandstateReturn a React element/node
  • butrenderIt’s a pure function and it doesn’t have side effects and it shouldn’t have side effects so we don’t want torenderIn doingthis.setStateSomething like this
  • Not responsible for final rendering
  • nullandbooleanWon’t be rendered

componentDidMount()

  • After the component is mounted, it is officially inserteddomThe nodes we need to do some binding can be done here
  • Easy to do some subscriptions or listening here
  • We can make some changes here as wellstateThe operation that will trigger againrender(Not the re-rendering of the browser page) but try to avoid doing so. Why bother
  • andconstructorEach will only trigger once

The update is updated

Since it is an update, it means that all of the following will be triggered in order!

Is not all, of course, such component internal state update won’t trigger UNSAFE_componentWillReceiveProps and getDerivedStateFromProps

But if it’s the state inside the component that updates the child component that uses the state here (the props state of the child component and the parent component) then it’s going to follow the rules and the child component is going to trigger these cycles and the components are going to follow these mechanisms

UNSAFE_componentWillReceiveProps(nextProps, nextState)

    UNSAFE_componentWillReceiveProps(nextProps, nextState) {
        if (this.state.visible ! == nextProps.visible) {this.setState({ visible: nextProps.visible })
        }
    }
Copy the code
  • Receive two parameters, one for the next timepropsAnd the next timestateWe can compare two changes in it and then do something
  • But it’s also easy to get bugs that we can’t predict
  • I am very sorry that the period name here was written wrong and no one reminded me ~

static getDerivedStateFromProps(props, state)

  • Same as above
  • Note the internal componentstateDirect changes are not triggered here if necessarythis.forceUpdate(callback)Same as above
  • If it ispropsData changes to trigger this cycle to spawn againstateThe trigger here is becausepropsNot just inside the componentsstatechange

shouldComponentUpdate(nextProps, nextState)

The official view is that state should be rerendered every time it is updated. For the most part, we should follow the rules of rendering

Most of them occur when the functions or state are out of control and render is frequently triggered, such as a long countdown

Existing only as an optimization can also be seen using PureComponent to shallow compare components

If you’re using a purely functional component and you want to achieve the same effect or purpose, you can use react.Memo ()

You can also use useMemo if you are also learning or using hooks

    shouldComponentUpdate(nextProps, nextState){
        if (this.props.value ! == nextProps.value) {return true
        }
        return false
    }
Copy the code
  • Receive two parameters the next time you get thempropsAnd the next time you get itstate.
  • This period isrenderThe last cycle before rendering represents whetherrender(exceptcomponentWillUpdateTo be scrapped).
  • Be sure to return one at the endfalseIt means don’t render or there will be unexpected effects.
  • inreturn falseCan be based on the currentthis.props || this.stateAnd so on, some of the values in there need to be renderedreturn true.
  • If you want to determine whether the render condition is going to use a loop orJSON.parse JSON.stringifyEqualization and deserialization may perform worse than no deserialization

UNSAFE_componentWillUpdate(nextProps, nextState)

  • Called immediately before the update happens you can’t call it from herethis.setState()ordispatchEtc triggers the component to update again
  • It is not reasonable to do any operation at this timepropsorstateThe changes again led to the unimaginable side effects of repetitive work
  • If you do need to move, pleasecomponentDidUpdate
  • The official abolishment is very nice!!

getSnapshotBeforeUpdate(prevProps, prevState)

  • This method will submit the render results toDOMIt can return an argument that was called before
  • This parameter is defined bycomponentDidUpdate(prevProps, prevState, snapshot)The third parameter of the method is received
  • The official word is that a component can be changed from a component before it changesDOMCapture some information (such as scroll position) in
  • I haven’t come across scenarios that are too detailed and unclear

render()

  • All sorts of filtering data into strings diff algorithms update parts change parts and so on and then generate nodes ditto

componentDidUpdate(prevProps, prevState, snapshot)

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (this.props.value ! == prevProps.value) {this.changeValue(this.props.value)
        }
    }
Copy the code
  • Called immediately after an update occurs. You can do some finishing touches after you update the DOM, which means that the first mount will never trigger don’t get me wrong
  • We can do some of the original use hereUNSAFE_componentWillUpdateDid something based on last timeprops stateA logical or business need to be triggered to be different from the next one
  • But andUNSAFE_componentWillUpdateIt’s different. This is the last onepropsandstate

When unloading

componentWillUnmount()

  • We can wrap things up here clearing timers, subscriptions, listening, etc
  • Most of the time there are somethis.setStateA warning that you cannot modify a component that does not exist is even an error
  • The component has been uninstalled (destroyed) asynchronouslythis.setStateStill working on the destroyedstateOf course not.
  • So sometimes we need the following postures
componentWillUnmount() {
    this.setState = (state, callback) = > { return }
    window.removeEventListener()
    clearInterval()}Copy the code

This is I have learned to use a little later accumulated notes sorted out for reference only if there is wrong to write there is omission welcome to point out in time