简体   繁体   中英

react lifecycle methods understanding

I am a newbie to React.js and I am trying hard to understand several methods in the React lifecycle methods.

So far, I have something that confuses me:

1)

As far as I understand, the difference between componentWillUpdate and componentWillReceiveProps is that componentWillReceiveProps will be called when the parent changes the props and we can use setState (setState of this child inside componentWillReceiveProps ).

for example: react-table-sorter-demo

var App = React.createClass({
  getInitialState: function() {
    return {source: {limit: "200", source: "source1"}};
  },
  handleSourceChange: function(source) {
    this.setState({source: source});
  },
  render: function() {
    return (
      <div>
        <DataSourceSelectors onSourceChange={this.handleSourceChange} source={this.state.source} />
        <TableSorter dataSource={urlForDataSource(this.state.source)} config={CONFIG} headerRepeat="5" />
      </div>
    );
  }
});

In TableSorter, we have

componentWillReceiveProps: function(nextProps) {
    // Load new data when the dataSource property changes.
    if (nextProps.dataSource != this.props.dataSource) {
      this.loadData(nextProps.dataSource);
    }
  }

meaning when we change this.state.source , we will expect componentWillReceiveProps to be called in TableSorter.

However, I don't quite understand how to use componentWillUpdate in this case, the definition of componentWillUpdate is

componentWillUpdate(object nextProps, object nextState)

How can we pass nextState from parent into child? Or maybe I am wrong, is the nextState passed from the parent element?

2) method componentWillMount confuses me because in the official documentation, it says that

Invoked once, both on the client and server, immediately before the initial rendering occurs.

In this case, if I use setState in this method, it will override the getInitialState since it will be called once only initially. In this case, what is the reason to set the parameters in the getInitialState method. In this particular case, we have:

  getInitialState: function() {
    return {
      items: this.props.initialItems || [],
      sort: this.props.config.sort || { column: "", order: "" },
      columns: this.props.config.columns
    };
  },
  componentWillMount: function() {
    this.loadData(this.props.dataSource);
  },
  loadData: function(dataSource) {
    if (!dataSource) return;

    $.get(dataSource).done(function(data) {
      console.log("Received data");
     this.setState({items: data});
     }.bind(this)).fail(function(error, a, b) {
      console.log("Error loading JSON");
     });
  },

items will be overriddene initially and why do we still need items: this.props.initialItems || [] items: this.props.initialItems || [] in the getInitialState method?

Hope you can understand my explanation, and please give me some hints if you have any.

1) componentWillReceiveProps is called before componentWillUpdate in React's update lifecycle. You are right that componentWillReceiveProps allows you to call setState . On the other hand componentWillUpdate is a callback to use when you need to respond to a state change.

The fundamental difference between props and state is that state is private to the component. That's why neither a parent component or anybody else can manipulate the state (eg call setState ) of the component. So the default workflow for the parent-child component relationship would be the following:

  • Parent passes new props to the child
  • Child handles new props in 'componentWillReceiveProps', calls setState if necessary
  • Child handles new state in 'componentWillUpdate' - but if your component is stateful, handling props in 'componentWillReceiveProps' will be enough.

2) You provided quite a good code example to illustrate the difference. Default values set in getInitialState will be used for initial rendering. The loadData call from componentWillMount will initiate an AJAX request which may or may not succeed - moreover it is unknown how long it will take to complete. By the time the AJAX request completes and setState is called with new state, the component will be rendered in the DOM with default values. That is why it makes total sense to provide default state in getInitialState .

Note: I found Understanding the React Component Lifecycle article a huge help for understanding React's lifecycle methods.

Four phases of a React component lifecycle

Initialization

Mounting

Update

Unmounting

Here's a quick walkthrough of the different methods of the lifeCycle of a component. You must have good understanding of the lifecycle methods to code efficiently in react.

Life Cycle Phase Methods

Methods in Mounting Phase:

This phase begins when an instance of a component is created and when it gets rendered into the DOM.

1. constructor(props) - it is called when the component is first initialized. This method is only called once.
2. componentWillMount() - it is called when a component is about to mount.
3. render() -it is called when a component is rendered.
4. componentDidMount() - it is called when a component has finished mounting.

Methods in Updating Phase:

This phase begins when a component's properties (aka props) or state changes.

1. componentWillReceiveProps(nextProps) - it is called when a component has updated and is receiving new props.
2. shouldComponentUpdate(nextProps, nextState) - it is called after receiving props and is about to update. If this method returns false, componentWillUpdate(), render(), and componentDidUpdate() will not execute.
3. componentWillUpdate(nextProps, nextState) - it is called when a component is about to be updated.
4. render() - called when a component is rerendered.
5. componentDidUpdate(prevProps, prevState) - it is called when a component has finished updating.

Methods in Unmounting Phase:

This phase begins when a component is being removed from the DOM.

1. componentWillUnmount() - it is called immediately before a component unmounts.

Ref: https://hackernoon.com/reactjs-component-lifecycle-methods-a-deep-dive-38275d9d13c0

Here is amazing diagram of React lifecycle methods( made by Dan Abramov ) 在此处输入图片说明

Interactive version of this diagram

Best Article I have ever read to understand the React Component Lifecycle :

Understanding the React Component Lifecycle

A component lifecycle method is a function that we can optionally define inside our class-based components. If we decide to implement these methods they will be called automatically by React at certain points during a components lifecycle.

A component will be created and show up in the DOM or browser and we can do something like this.setState() which will cause the component to re-render and in theory at some point in time a component will be removed from the DOM altogether and stop showing its contents on the screen.

That entire series of events is what is referred to as the components lifecycle.

These lifecycle methods are called at very distinct times during a lifecycle.

There is the constructor(props) function, which is a function we can optionally define and if we do it will be automatically called when a new instance of the component is created.

There is the render() method, which is not optionally, we have to define it. The render() method is a lifecycle function, it gets called at some point during the lifecycle of a component.

We start off with constructor(props) being called then the render() method will be called, returns some amount of jsx and the content becomes visible on the screen.

Then there is another series of lifecycle methods being called at different points in time.

First, immediately after a component shows up on the screen of the browser, a lifecycle method called componentDidMount() will be called. That means that if we define a function inside our class, outside the constructor(props) , right above the render() method we can define a method called componentDidMount() like so:

componentDidMount() {

}

render() {

}

This function will be automatically called one time, when the component first gets rendered onto the screen. We can put code inside for setting up or do some initial data loading or a wide variety of operations that we might want to do one time, when the component first shows up.

After that method gets called, the component will sit around and wait for an update. The update will come in the form of this.setState() .

Once done, the component will update or re render itself which will call another lifecycle method called, componentDidUpdate() . If we define that function, it will be called automatically, anytime that component updates itself.

The component will sit around and wait for another update and the componentDidUpdate() again or numerous amounts of time.

At some point, we might want to stop the componentDidUpdate() component and thats where we implement the componentWillUnmount() and this is a method we want to call when we want to do cleanup of our component.

source code lifecycle methods in React

you can create component and run your project. check console in the browser for render log.

import React, { Component } from 'react'

class LifecycleA extends Component {
    constructor(props) {
        super(props)

        this.state = {
            name: 'triadmoko'
        }
        console.log('lifecycle A constructor');
    }

    static getDerivedStateFromProps(props, state) {
        console.log('lifecycle A getDerivedStateFromProps');
        return null
    }
    componentDidMount = () => {
        console.log('lifecylce A componentDidMount');
    }
    render() {
        console.log('lifecycle A render');

        return (
            <div>LifecycleA</div>
        )
    }
}

export default LifecycleA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM