如何为Immutable.js对象编写TypeScript接口?

时间:2018-05-28 13:58:58

标签: reactjs typescript immutable.js typechecking

假设我们有以下界面User

interface User {
  id: number;
  name: string;
  bag: Item[];
}

我现在可以定义一个React组件:

interface UserComponentProps {
  user: User;
}
interface UserComponentState {}

class UserComponent extends React.Component<UserComponentProps, UserComponentState> {

这很好,因为现在我可以在组件中进行类型检查,但是存在一个问题:用户不是不可变的,所以当用户没有改变时很难阻止UserComponent呈现。

但是如果我将我的用户存储为Immutable对象,我的组件将如下所示:

interface UserComponentProps {
  user: Immutable.Map<string, any>;
}
interface UserComponentState {}

class UserComponent extends React.Component<UserComponentProps, UserComponentState> {

如何为这类对象定义接口?

1 个答案:

答案 0 :(得分:0)

如果props发生了变化,React的Component会重新渲染,所以答案很大程度上取决于你如何为渲染创建props

一个简单的例子可以给你一个想法:

const bag = Immutable.List([{name:"bagItem1"}]);
console.log(bag.toJS() === bag.toJS())
<script src="https://facebook.github.io/immutable-js/immutable.js"></script>

这是什么意思?这意味着,如果您使用Immutable存储Item[],然后将UserComponent渲染为:

<UserComponent
   id={1}
   name={"some name"}
   bag={store.getIn(["bag", "items"]).toJS()}
   />

然后在每个商店突变,即使包从未更改过,UserComponent将收到bag的新对象,并将强制重新呈现。

对于plain被反对的道具,您可以考虑使用React.PureComponent,这将为您进行浅层比较,但如果您需要传递对象数组,那么您通常有两个解决方案:

  1. 为您shallComponentUpdate实施Component方法,您可以在其中手动比较prevPropsnextProps,并返回boolean,表明{ {1}}将被重新呈现

  2. 请勿使用Component进行存储。完全!我的公司做到了这一点,我们从不后悔。 (你也节省了150kb :))

  3. 要替换Immutable,您必须学习正确构造和变异存储的视图实践。有很多good articles