如何在React中动态列出组件而没有冗余渲染?

时间:2017-09-19 07:57:48

标签: reactjs

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>
         );
       }
     });

我想添加&#34; Cherry&#34;列出。 before

按原样,它会冗余地重绘所有项目。我希望orange1和apple2需要保持状态而不重写。

动态列表组件的设计更好? after

1 个答案:

答案 0 :(得分:4)

将列表项提取到其自己的纯组件中,确保仅在数据实际更改时更改道具,并使用key道具让反应知道列表中的哪个项目。这样,列表将重新渲染,但子FruitItem只会在道具更改时重新渲染。

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]}
    />
  );
})

请参阅working codepen,检查控制台以观察重新渲染