选择是否使用props / state在render()中显示组件会导致每次重绘吗?

时间:2017-02-13 11:28:27

标签: reactjs

以下两个相同的表现是否明智?第一个示例是否会在每次更新Component1道具时重新呈现Component2MyComponent

import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { selectShowComponent1, selectShowComponent2 } from './selectors';

@connect(createStructuredSelector({
  showComponent1: selectShowComponent1,
  showComponent2: selectShowComponent2,
}))
class MyComponent extends React.PureComponent {
  static propTypes = {
    showComponent1: React.PropTypes.bool,
    showComponent2: React.PropTypes.bool,
  };

  render() {
    const { showComponent1, showComponent2 } = this.props;
    return (
      <div>
        {showComponent1 ? (<Component1>shown 1</Component1>) : ''}
        {showComponent2 ? (<Component2>shown 2</Component2>) : ''}
      </div>
    );
  }
}

export default MyComponent;
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { selectShowComponent1, selectShowComponent2 } from './selectors';

@connect(createStructuredSelector({
  showComponent1: selectShowComponent1,
  showComponent2: selectShowComponent2,
}))
class MyComponent extends React.PureComponent {
  static propTypes = {
    showComponent1: React.PropTypes.bool,
    showComponent2: React.PropTypes.bool,
  };

  render() {
    const { showComponent1, showComponent2 } = this.props;
    return (
      <div>
        <Component1 renderMe={showComponent1}>shown 1</Component1>
        <Component2 renderMe={showComponent2}>shown 2</Component2>
      </div>
    );
  }
}

export default MyComponent;

1 个答案:

答案 0 :(得分:1)

第一个将每次重新渲染,而第二个则不会。原因是动态生成的组件(在这种情况下,动态cos它们是三元运算符的结果)每次从动态上下文返回时都会得到一个新密钥。而这个密钥就是React在内部用于唯一标识组件的内容。

所以我相信如果你给他们明确的钥匙:

    {showComponent1 ? (<Component1 key="1">shown 1</Component1>) : ''}
    {showComponent2 ? (<Component2 key="2">shown 2</Component2>) : ''}

然后在理论上应该阻止它们被重新渲染,但这并不理想,因为在某些情况下手动分配键可能意味着组件可能无法在您实际需要时重新渲染。