React:是否可以将项目添加到列表而不更新其同级物品?

时间:2019-02-12 22:12:19

标签: javascript reactjs

假设我有:

class Item extends React.Component {
  render() {
    console.log('Let's assume this does something slow...');
    return <li>{this.props.text}</li>;
  }
}


class List extends React.Component {
  constructor() {
    super();
    this.state = {
      items: [],
    };
  }
  addItem = text => {
    this.setState({
      // Mutates the array reference... is there a way around it?
      items: this.state.items.concat({ id: Math.random(), text }),
    });
  };
  render() {
    return (
      <div>
        <button onClick={() => this.addItem(Math.random())}>Add Item</button>
        <ul>
          // This will run on every render, re-rendering the whole list...
          {this.state.items.map(item => (
            <Item key={item.id} text={item.text} />
          ))}
        </ul>
      </div>
    );
  }
}

是否可以完全保留现有列表,而我只需在顶部/底部添加一个新项目,而无需调用其同级的render()

1 个答案:

答案 0 :(得分:3)

React Component将始终被重新渲染,但是PureComponent实现的shouldComponentUpdate具有较浅的属性和状态比较,因此除非这些属性是改变了。

class Item extends React.PureComponent {
  render() {
    console.log("Let's assume this does something slow...");
    return <li>{this.props.text}</li>;
  }
}

class List extends React.Component {
  state = {
    items: []
  };

  addItem = text => {
    this.setState(prevState => {
      return { items: [...prevState.items, { id: Math.random(), text }] };
    });
  };

  render() {
    return (
      <div>
        <button onClick={() => this.addItem(Math.random())}>Add Item</button>
        <ul>
          {this.state.items.map(item => (
            <Item key={item.id} text={item.text} />
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<List />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>