React: update one item in a list without recreating all items

前端 未结 6 604
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 05:27

Let\'s say I have a list of 1000 items. And I rendering it with React, like this:

class Parent extends React.Component {
  render() {
    // this.state.list is a         


        
6条回答
  •  悲&欢浪女
    2021-01-30 05:44

    When you change your data, react default operation is to render all children components, and creat virtual dom to judge which component is need to be rerender.

    So, if we can let react know there is only one component need to be rerender. It can save times.

    You can use shouldComponentsUpdate in your list component.

    If in this function return false, react will not create vitual dom to judge.

    I assume your data like this [{name: 'name_1'}, {name: 'name_2'}]

    class Item extends React.Component {
      // you need judge if props and state have been changed, if not
      // execute return false;
      shouldComponentUpdate(nextProps, nextState) { 
        if (nextProps.name === this.props.name) return false;
    
        return true;
      }
      render() {
        return (
          
  • {this.props.name}
  • ) } }

    As react just render what have been changed component. So if you just change one item's data, others will not do render.

提交回复
热议问题