加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:11:35 所属栏目:百科 来源:网络整理
导读: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
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>
         );
       }
     });

我想在列表中添加“Cherry”.

before

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

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

after

解决方法

将列表项提取到其自己的纯组件中,确保仅在数据实际更改时更改props,并使用key prop让反应知道列表中的哪个项.这样列表将重新渲染,但子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,检查控制台以查看重新渲染

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读