React:为什么只调用组件的构造函数一次?

时间:2015-03-16 10:36:31

标签: reactjs

following example中,点击Item 2时,会显示Second 1而不是Second 2。为什么?你会如何解决这个问题?


var guid = 0;

class Content extends React.Component {
  constructor() {
    guid += 1;
    this.id = guid;
    console.log('ctor', this.id); // called only once with 1
  }
  render() {
    return (
      <div className="content">
        {this.props.title} - {this.id}
      </div>
    );
  }
}

class MyApp extends React.Component {
  constructor() {
    this.items = ['Item 1', 'Item 2'];
    this.state = {
      activeItem: this.items[0]
    };
  }
  onItemClick(item) {
    this.setState({
      activeItem: item
    });
  }
  renderMenu() {
    return (
      <div className="menu">
        <div onClick={this.onItemClick.bind(this, 'Item 1')}>Item 1</div>
        <div onClick={this.onItemClick.bind(this, 'Item 2')}>Item 2</div>
      </div>
    );
  }
  renderContent() {
    if (this.state.activeItem === 'Item 1') {
      return (
        <Content title="First" />
      );
    } else {
      return (
        <Content title="Second" />
      );
    }
  }
  render() {
    return (
      <div>
        {this.renderMenu()}
        {this.renderContent()}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:89)

React的reconciliation algorithm假设没有任何相反的信息,如果自定义组件出现在后续渲染中的相同位置,则它与之前的组件相同,因此重复使用之前的组件实例,而不是创建一个新实例。

如果您要实施componentWillReceiveProps(nextProps),您会看到被调用。

  

Different Node Types

     

<Header>元素不太可能生成一个看起来像<Content>将生成的DOM。而不是花时间尝试匹配这两个结构,React只是从头开始重新构建树。

     

作为推论,如果两个连续渲染中的同一位置有一个<Header>元素,您可能会看到一个非常相似的结构,值得探索它。

     

Custom Components

     

我们决定两个自定义组件是相同的。由于组件是有状态的,我们不能只使用新组件并将其称为一天。 React从新组件中获取所有属性,并在前一个组件上调用component[Will/Did]ReceiveProps()

     

之前的组件现已投入使用。调用其render()方法,并使用新结果和先前结果重新启动diff算法。

如果给每个组件a unique key prop,React可以使用key更改来推断组件实际已被替换,并将从头开始创建一个新组件,从而为其提供完整的组件生命周期。 / p>


  renderContent() {
    if (this.state.activeItem === 'Item 1') {
      return (
        <Content title="First" key="first" />
      );
    } else {
      return (
        <Content title="Second" key="second" />
      );
    }
  }
相关问题