小编典典

反应生命周期方法的理解

reactjs

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

到目前为止,我感到有些困惑:

1)

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

例如: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>
    );
  }
});

在TableSorter中,我们有

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

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

但是,我不太了解如何componentWillUpdate在这种情况下使用,定义componentWillUpdate

componentWillUpdate(object nextProps, object nextState)

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

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

在初始渲染发生之前立即在客户端和服务器上调用一次。

在这种情况下,如果我在此方法中使用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: this.props.initialItems || []在getInitialState方法中使用?

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


阅读 272

收藏
2020-07-22

共1个答案

小编典典

1)在React的更新生命周期中componentWillReceiveProps被调用componentWillUpdate。您说对了,componentWillReceiveProps可以打电话给您setState。另一方面componentWillUpdate是当您需要响应状态更改时使用的回调。

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

  • 父母将新道具传递给孩子
  • 子代处理’componentWillReceiveProps’中的新道具,setState必要时调用
  • 子级在’componentWillUpdate’中处理新状态-但是,如果您的组件是有状态的,则在’componentWillReceiveProps’中处理道具就足够了。

2)您提供了一个很好的代码示例来说明差异。设置的默认值getInitialState将用于初始渲染。loadData来自的呼叫componentWillMount会发起一个AJAX请求,该请求可能会成功也可能不会成功-
而且,未知需要多长时间才能完成。到AJAX请求完成并setState以新状态调用时,该组件将使用默认值呈现在DOM中。因此,在中提供默认状态是很有意义的getInitialState

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

2020-07-22