【问题标题】:Mobx Generic Observer using Typescript typing使用 Typescript 打字的 Mobx 通用观察者
【发布时间】:2020-12-22 18:51:31
【问题描述】:

我想在 mobx 的 observer() 中封装以下函数,但似乎无法弄清楚如何在保持通用类型的同时做到这一点(或者如果可能的话):

interface GenericProps<T> {
  arg: T;
}
const foo: <T>(props: GenericProps<T>) => T = (props) => props.arg;

这是一个全局导出函数,所以不能使用 @observer 装饰器(我认为),我需要使用 mobx-lite-react 中的 observer() 函数。

我想要的是类似的东西

interface GenericProps<T> {
  arg: T;
}
const foo = observer<T>((props: GenericProps<T>) => props.arg);

可能与 https://github.com/mobxjs/mobx-react-lite/issues/243 有关,但从对话中我不清楚在我的案例中我将如何实现通用观察者。

【问题讨论】:

    标签: reactjs typescript typescript-typings mobx mobx-react-lite


    【解决方案1】:
    1. 你的sample不是react组件,需要匹配React.FunctionComponent接口
    const foo_1: <T>(props: GenericProps<T>) => React.ReactElement | null = (props) => <>{JSON.stringify(props.arg)}</>;
    
    1. 添加观察者(由于 TS 3.4 或 3.5 的改进,这应该已经可以工作了)
    const foo_2: <T>(props: GenericProps<T>) => React.ReactElement | null = observer((props) => <>{JSON.stringify(props.arg)}</>);
    
    1. 如果在较旧的 TS 上,您需要将类型声明移动到函数本身(注意 extends unknown 告诉编译器这是通用定义而不是 JSX 标记,不需要指定返回类型,因为它会被推断)
    const foo_3 = observer(<T extends unknown>(props: GenericProps<T>) => <>{JSON.stringify(props.arg)}</>);
    

    【讨论】:

    • 是的,2. 为我工作 - 谢谢!关键是我没有正确输入函数;那么观察者本身没有对该类型的直接引用,但这对我的用例来说没问题。
    【解决方案2】:

    这是你想要的吗?

    interface GenericProps<T> {
      arg: T
    }
    
    const foo = <T extends IReactComponent>(props: GenericProps<T>) => observer(props.arg)
    

    我不太明白,因为在第一个示例中,您有返回另一个函数的函数,但在第二个示例中,您只需将函数传递给 observer,但这是不可能的,因为观察者只接受扩展 IReactComponent

    【讨论】:

    • 感谢您的帮助!第一个问题,IReactComponent 是什么?回复:您的问题,传递给观察者的函数只是根据存储在 mobx 中的值更新一些存储(它不返回任何内容/无效),因此希望将其包装在观察者中,以便在必要时重新运行逻辑。
    • IReactComponent 是 MobX 辅助类型,基本上是type IReactComponent&lt;P = any&gt; = React.ClassicComponentClass&lt;P&gt; | React.ComponentClass&lt;P&gt; | React.FunctionComponent&lt;P&gt; | React.ForwardRefExoticComponent&lt;P&gt;。如果你只想更新商店而不渲染任何东西,你为什么还要使用observerreactionautorun 不是会更好吗?
    猜你喜欢
    • 2020-08-24
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多