Javascript 反应生命周期方法理解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29873730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:09:51  来源:igfitidea点击:

react lifecycle methods understanding

javascriptreactjslifecycle

提问by Guifan Li

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

我是 React.js 的新手,我正在努力理解 React 生命周期方法中的几种方法。

So far, I have something that confuses me:

到目前为止,我有一些让我感到困惑的事情:

1)

1)

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

据我了解,之间的差别componentWillUpdate,并componentWillReceiveProps是,componentWillReceiveProps当父改变了道具,我们可以使用的setState(这个孩子里面的setState将被调用componentWillReceiveProps)。

for example: react-table-sorter-demo

例如: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

在 TableSorter 中,我们有

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 componentWillReceivePropsto be called in TableSorter.

这意味着当我们更改时this.state.source,我们将期望componentWillReceiveProps在 TableSorter 中被调用。

However, I don't quite understand how to use componentWillUpdatein this case, the definition of componentWillUpdateis

但是,我不太明白componentWillUpdate在这种情况下如何使用,的定义componentWillUpdate

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?

我们如何将 nextState 从父级传递给子级?或者我错了,nextState 是从父元素传递过来的吗?

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

2)方法componentWillMount让我感到困惑,因为在官方文档中,它说

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:

在这种情况下,如果我在此方法中使用 setState,它将覆盖 getInitialState,因为它最初只会被调用一次。在这种情况下,在getInitialState方法中设置参数的原因是什么。在这种特殊情况下,我们有:

  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 || []in the getInitialState method?

项目最初将被覆盖,为什么我们仍然需要 items: this.props.initialItems || []在 getInitialState 方法中?

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

希望你能理解我的解释,如果你有任何提示,请给我一些提示。

回答by Yevgen Safronov

1) componentWillReceivePropsis called before componentWillUpdatein React's update lifecycle. You are right that componentWillReceivePropsallows you to call setState. On the other hand componentWillUpdateis a callback to use when you need to respond to a state change.

1)在 React 的更新生命周期componentWillReceiveProps之前被调用componentWillUpdate。你是对的,componentWillReceiveProps允许你打电话setState。另一方面componentWillUpdate是当您需要响应状态更改时使用的回调。

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 (e.g. call setState) of the component. So the default workflow for the parent-child component relationship would be the following:

props 和 state 之间的根本区别在于 state 是组件私有的。这就是为什么父组件或其他任何人都不能操纵组件的状态(例如调用setState)的原因。因此,父子组件关系的默认工作流程如下:

  • Parent passes new props to the child
  • Child handles new props in 'componentWillReceiveProps', calls setStateif necessary
  • Child handles new state in 'componentWillUpdate' - but if your component is stateful, handling props in 'componentWillReceiveProps' will be enough.
  • 父母将新道具传递给孩子
  • 孩子处理“componentWillReceiveProps”中的新道具,setState必要时调用
  • Child 在 'componentWillUpdate' 中处理新状态 - 但如果你的组件是有状态的,在 'componentWillReceiveProps' 中处理 props 就足够了。

2) You provided quite a good code example to illustrate the difference. Default values set in getInitialStatewill be used for initial rendering. The loadDatacall from componentWillMountwill 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 setStateis 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.

2)您提供了一个很好的代码示例来说明差异。中设置的默认值getInitialState将用于初始渲染。loadData来自的调用componentWillMount将发起一个 AJAX 请求,该请求可能成功也可能不成功——而且不知道需要多长时间才能完成。当 AJAX 请求完成并setState以新状态调用时,组件将在 DOM 中以默认值呈现。这就是为什么在getInitialState.

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

注意:我发现理解 React 组件生命周期一文对理解 React 的生命周期方法有很大帮助。

回答by Aftab22

Four phases of a React component

React 组件的四个阶段

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 in react.

的一个组件。您必须对在 React 中编码的生命周期方法有很好的理解。

Methods in Mounting Phase:

安装阶段的方法:

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

当组件的实例被创建并被渲染到 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.

1. constructor(props)- 它在组件第一次初始化时被调用。这个方法只调用一次。
2. componentWillMount()- 当组件即将安装时调用。
3. render()- 组件渲染时调用。
4. componentDidMount()- 当组件完成安装时调用它。

Methods in Updating Phase:

更新阶段的方法:

It begins when a component's properties 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.

1. componentWillReceiveProps(nextProps)- 当组件更新并接收新道具时调用。
2. shouldComponentUpdate(nextProps, nextState)- 收到道具后调用,即将更新。如果此方法返回 false,则 componentWillUpdate()、render() 和 componentDidUpdate() 将不会执行。
3. componentWillUpdate(nextProps, nextState)- 当组件即将更新时调用。
4. render()- 重新渲染组件时调用。
5. componentDidUpdate(prevProps, prevState)- 当组件完成更新时调用它。

Methods in Unmounting Phase:

卸载阶段的方法:

It begins when a component is being removed from the DOM.

它从组件从 DOM 中移除时开始。

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

1. componentWillUnmount()- 在组件卸载之前立即调用它。

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

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

回答by Himanshu Teotia

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

我读过的最好的文章来理解 React 组件生命周期:

Understanding the React Component Lifecycle

理解 React 组件生命周期

回答by Igor Alemasow

Here is amazing diagram of React lifecycle methods(made by Dan Abramov) enter image description here

这是 React 生命周期方法的惊人图表(由 Dan Abramov 制作在此处输入图片说明

Interactive version of this diagram

此图的交互式版本

回答by Daniel

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.

组件生命周期方法是一个函数,我们可以选择在基于类的组件中定义它。如果我们决定实现这些方法,它们将在组件生命周期的某些时刻被 React 自动调用。

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.

一个组件将被创建并显示在 DOM 或浏览器中,我们可以做一些类似的事情this.setState(),这将导致组件重新渲染,理论上在某个时间点,组件将完全从 DOM 中删除并停止显示其内容屏幕上。

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.

constructor(props)函数,这是一个我们可以选择定义的函数,如果我们这样做,它将在创建组件的新实例时自动调用。

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.

有一个render()方法,它不是可选的,我们必须定义它。该render()方法是一个生命周期函数,它在组件生命周期的某个时刻被调用。

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.

我们从constructor(props)被调用开始,然后render()将调用该方法,返回一些 jsx 并且内容在屏幕上可见。

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()会立即调用一个被调用的生命周期方法。这意味着如果我们在我们的类中定义一个函数constructor(props),在render()方法的正上方,我们可以定义一个componentDidMount()像这样调用的方法:

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().

调用该方法后,组件将等待更新。更新将以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.

完成后,组件将更新或重新呈现自身,这将调用另一个名为 的生命周期方法componentDidUpdate()。如果我们定义了该函数,它将在该组件自身更新时自动调用。

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

该组件将坐在那里等待另一个更新和componentDidUpdate()再次或大量的时间。

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.

在某些时候,我们可能想要停止componentDidUpdate()组件,这就是我们实现的地方componentWillUnmount(),这是我们想要清理组件时要调用的方法。