7

Here is an online sample.

var FruitList = React.createClass({
      render : function() {
        return (
          <div className="container">
            <ul className="list-group text-center">
              {
                Object.keys(this.props.fruits).map(function(key) {
                  count = count + 1;
                  return <li className="list-group-item list-group-item-info">{this.props.fruits[key]+count}</li>
                }.bind(this))
              }
            </ul>
           </div>
         );
       }
     });

I want to add "Cherry" to list. before

As is, it redraws all items redundantly. I hope that orange1 and apple2 need to keep their state with no redraw redundantly.

What the design for dynamic list components is better? after

1

1 Answer 1

4

Extract your list item into it's own pure component, make sure the props only change when the data actually changes, and use the key prop to let react know which item in the list. This way the list will re-render, but the child FruitItem will only re-render when the props change.

import React, {PureComponent} from 'react';

-

class FruitItem extends PureComponent {
  render() {
    console.log('FruitItem render', this.props.name);
    return (
      <li className="list-group-item list-group-item-info">
        {this.props.name}
      </li>
    );
  }
}

-

Object.keys(this.props.fruits).map((key) => {
  return (
    <FruitItem
      key={key}
      name={this.props.fruits[key]}
    />
  );
})

See working codepen, check the console to watch for re-renders

1
  • Thank you Austin, That's all I wanted
    – TonyY
    Commented Sep 19, 2017 at 9:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.