有效地计算来自反应道具的派生数据

Efficiently computing derived data from react props

我们正在 react/redux 应用程序中实施性能优化​​。这些优化的一部分包括引入重新选择。这对于直接从状态派生的数据非常有效。但是从其他道具派生的数据呢?

示例:

我们有 3 个组件 Feed FeedItemContact(Contact 是显示用户联系信息的组件)。

a FeedItem 获取表示提要中项目的对象,提要项目的属性之一是参与者对象。这个对象就像一个用户,但有点不同(这很糟糕但无法更改)。这意味着如果我想为这个演员呈现 Contact,我需要创建一个新对象,将属性从演员映射到用户。在每次渲染时创建一个新对象是一种性能反模式,因为我们使用的是浅层相等性检查。

例如代码:

<Contact
  user={{
    photoUrl: actor.photo.smallPhotoUrl,
    Id: actor.id,
    Name: actor.name,
  }}
</Contact>

有解决这个问题的模式吗? reselect 只支持从 redux state 派生的数据,这基本上是从 props 派生的数据。

您可以传递任何您想要重新选择的选择器方法。它不一定是状态和道具。这恰好是它最常见的用例。如果它生成了带有任意数量参数的选择器,您可以调用它。

这是您可以使用它的一种方式:

function convertActorToContactUser(actor) {
  return {
    photoUrl: actor.photo.smallPhotoUrl,
    Id: actor.id,
    Name: actor.name,
  };
}

class ActorContact extends Component {
  constructor(...args) {
    super(...args);
    this.getUser = createSelector(
      () => this.props.actor,
      convertActorToContactUser
    );
  }

  render() {
    return <Contact user={this.getUser()} />
  }
}