React16 version later, changed the react of life cycle, abandoned the previous componentWillMount (), componentWillReceiveProps (), componentWillUpdate (); Added static getDerivedStateFromProps() and getSnapshotBeforeUpdate().

The previous project used the old life cycle, and I did not know much about the new life cycle. Now I have time, and I want to know more about it.

Here are some questions to learn about the new life cycle.

Question 1: Why scrap the original life cycle?

Deprecation lifecycle:

componentWillMount

componentWillReceiveProps

componentWillUpdate

Deprecated lifecycle methods, often misunderstood and abused, are unsafe. * * such as:

1: Get data in componentWillMount to avoid rendering null the first time. Actually, this isn’t true because React always executes render immediately after componentWillMount. If data is not available when componentWillMount is triggered, the first render will still show loaded status regardless of where you initialized the data. This is why, in the vast majority of cases, moving the fetch data to componentDidMount has no obvious effect.

2: Subscribed to external events while the component is mounted, which can cause memory leaks for server rendering (which never calls componentWillUnmount) and asynchronous rendering (which can be interrupted before rendering is complete, resulting in not calling componentWillUnmount). It is often assumed that componentWillMount and componentWillUnmount come in pairs, but this is not guaranteed. React is only sure to call componentWillUnmount later to clean up after calling componentDidMount.

3. It is not safe to use componentWillUpdate in asynchronous mode because external callbacks may be called multiple times in an update. Instead, use the componentDidUpdate life cycle because it guarantees that each update will only be called once.

4, componentWillReceiveProps could be called multiple times during an update. Therefore, it is important to avoid side effects in this approach. Instead, use componentDidUpdate because it guarantees that each update will only be called once.

New lifecycle: Static getDerivedStateFromProps() is a pure function and cannot perform side effects (such as calling data asynchronously). Misoperation is largely avoided. Putting side effects on componentDidUpdate ensures that every update is called only once, rather than making multiple calls and getting stuck whether the update is complete or not.

You can go to the detailsThe react websiteCheck, very detailed.

Question 2: New life cycle role?

static getDerivedStateFromProps(props, state)
Copy the code

GetDerivedStateFromProps is called before the Render method is called (it is triggered before every render) and is called during initial mount and subsequent updates. It should return an object to update state, and if null is returned, nothing is updated.

If you need to perform side effects (for example, data extraction or animation) in response to changes in props, use componentDidUpdate instead

* * getDerivedStateFromProps and componentDidUpdate combination, basic can cover all componentWillReceiveProps usage scenarios. 民运分子

getSnapshotBeforeUpdate(prevProps, prevState)
Copy the code

GetSnapshotBeforeUpdate () is called before the last render output (submitted to the DOM node). It enables the component to capture some information (for example, scroll position) from the DOM before changes are made. Any return value for this life cycle is passed as an argument to componentDidUpdate(). The value of snapshot should be returned (or NULL).

Such as:

class ScrollingList extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Do we add new items to the list?
    // Capture the scroll position so we can adjust the scroll position later.
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // If our snapshot has a value, we just added a new item,
    // Adjust the scroll position so that these new items do not push the old items out of the view.
    // (where snapshot is the return value of getSnapshotBeforeUpdate)
    if(snapshot ! = =null) {
      const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; }}render() {
    return (
      <div ref={this.listRef}>{/ *... contents... * /}</div>); }}Copy the code

Problem three: Life cycle method calls

Lifecycle map addressThe projects. Wojtekmaj. Pl/react – lifec…

mount

When a component instance is created and inserted into the DOM, its lifecycle is called in the following order:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()
update

Updates are triggered when a component’s props or state changes. Component updates are called in the lifecycle order as follows:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()
uninstall

The following method is called when a component is removed from the DOM:

  • componentWillUnmount()
Error handling

When an error is thrown in a rendering process, lifecycle, or child component’s constructor, the following methods are called:

  • static getDerivedStateFromError()
  • componentDidCatch()

conclusion

The official website is really a good thing. If you look closely, you can find a lot of things. It is more detailed and systematic than other blogs.

In the past, I always encountered problems and solved them, so I had a one-sided understanding. This is why I checked the React new life cycle so many times, but I still didn’t remember it, and I still didn’t understand the cause and effect. This time, I learned it all over again.

Many are copied from the official website, write bad, please forgive me, you can go to the official website to check

React: React.docschina.org/