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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With