【问题标题】:How to write a TypeScript interface for Immutable.js objects?如何为 Immutable.js 对象编写 TypeScript 接口?
【发布时间】:2018-05-28 13:58:58
【问题描述】:

假设我们有以下接口User

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

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

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

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

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

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

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

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

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

【问题讨论】:

    标签: reactjs typescript immutable.js typechecking


    【解决方案1】:

    如果props 发生更改,React 的组件将重新渲染,因此答案很大程度上取决于您如何创建 props 进行渲染。

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

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

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

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

    然后在每次存储突变时,即使包从未更改,UserComponent 也会收到bag 的新对象并强制重新渲染。

    对于plain反对的道具,你可以考虑使用React.PureComponent,它会为你做浅比较,但如果你需要传递对象数组,那么你通常有两种解决方案:

    1. 为您实现shallComponentUpdate 方法Component,您可以在其中手动比较prevPropsnextProps,并返回boolean,表示是否应重新渲染Component

    2. 不要将Immutable 用于存储。完全!我的公司已经做到了,我们从不后悔。 (你也节省了 150kb :))

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

    【讨论】:

    • 完全不使用 Immutable 可能是一个不错的选择,我确实认为它会导致应用程序效率低下,但您并没有回答我的问题,即如何使用 Immutable 进行打字(这有助于记录并允许进行类型检查)。
    • 当用户未更改时,难以阻止 UserComponent 呈现。 这是我要回答的部分。我相信您误解了接口在这里的作用。当组件重新渲染时,接口无法影响。但是,如果您仍然只想打字,请查看 Immutable 的Record,示例herehere
    猜你喜欢
    • 2021-07-31
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2018-11-15
    • 2014-08-21
    • 2020-10-19
    • 2018-11-05
    相关资源
    最近更新 更多