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

假设我有1000个项目的列表。我用React渲染它,​​像这样:

class Parent extends React.Component {
  render() {
    // this.state.list is a list of 1000 items
    return <List list={this.state.list} />;
  }
}

class List extends React.Component {
  render() {
    // here we're looping through this.props.list and creating 1000 new Items
    var list = this.props.list.map(item => {
      return <Item key={item.key} item={item} />;
    });
    return <div>{list}</div>;
  }
}

class Item extends React.Component {
  shouldComponentUpdate() {
    // here I comparing old state/props with new
  }
  render() {
    // some rendering here...
  }
}

With a relatively long list map() takes about 10-20ms and I can notice a small lag in the interface.

使用相对较长的列表映射()需要大约10-20ms,我可以注意到界面中的小延迟。

Can I prevent recreation of 1000 React objects every time when I only need to update one?

每当我只需要更新一个时,我可以阻止重新创建1000个React对象吗?

5 个解决方案

#1


11

You can do it by using any state management library, so that your Parent doesn't keep track of this.state.list => your List only re-renders when new Item is added. And the individual Item will re-render when they are updated.

您可以使用任何状态管理库来执行此操作,以便您的父级不跟踪this.state.list =>您的列表仅在添加新项目时重新呈现。并且单个项目在更新时将重新呈现。

Lets say you use redux.

让我们说你使用redux。

Your code will become something like this:

您的代码将变为如下所示:

// Parent.js
class Parent extends React.Component {
  render() {        
    return <List />;
  }
}

// List.js
class List extends React.Component {
  render() {        
    var list = this.props.list.map(item => {
      return <Item key={item.key} uniqueKey={item.key} />;
    });
    return <div>{list}</div>;
  }
}

const mapStateToProps = (state) => ({
  list: getList(state)
});

export default connect(mapStateToProps)(List);


// Item.js
class Item extends React.Component {
  shouldComponentUpdate() {
  }
  render() {
  }
}

const mapStateToProps = (state, ownProps) => ({
  item: getItemByKey(ownProps.uniqueKey)
});

export default connect(mapStateToProps)(Item);

Of course, you have to implement the reducer and the two selectors getList and getItemByKey.

当然,您必须实现reducer和两个选择器getList和getItemByKey。

With this, you List re-render will be trigger if new elements added, or if you change item.key (which you shouldn't)

这样,如果添加了新元素,或者更改了item.key(不应该更改),将触发List重新渲染。

更多相关文章

  1. 在项目之间共享ASP.NET MVC部分视图
  2. AngularJS(1.5.8) - 如何直接从获取json对象的控制器中填充选择选
  3. 将子属性添加到jsdoc中的现有属性列表
  4. python数据类型二(列表和元组)
  5. 使用特定顺序的ID列表从Django数据库中获取记录
  6. 【项目实战】自监控-09-DataFrame索引操作(上篇)
  7. python传递列表作为函数参数
  8. Python基础(列表)第三天
  9. 用户输入从.csv文件生成新列表?

随机推荐

  1. php array_chunk函数怎么用
  2. php技术栈是什么
  3. php中的array_fill函数怎么用
  4. php怎么做页面静态化
  5. php中的array_combine函数怎么用
  6. php levenshtein函数怎么用
  7. php中的count_chars函数怎么用
  8. php中的array_search函数怎么用
  9. php中的str_word_count函数怎么用
  10. php中的array_slice函数怎么用