【问题标题】:React JS: How to get MobX store's state using observer in a custom hook?React JS:如何在自定义钩子中使用观察者获取 MobX 商店的状态?
【发布时间】:2021-01-22 18:44:41
【问题描述】:

用例:

我有一个自定义钩子useFoo,它需要根据存储中的bar 属性返回值,但打字稿会抛出错误。

代码:

export const useFoo = observer(() => {
// typescript throws error --^^^^^^^--

  const { bar } = store;

  return bar ? 'x' : 'y';
});

打字稿错误:

Argument of type '() => "x" | "y"' is not assignable to parameter of type 'IReactComponent<any>'.
  Type '() => "x" | "y"' is not assignable to type 'FunctionComponent<any>'.
    Type '"x" | "y"' is not assignable to type 'ReactElement<any, any> | null'.
      Type '"x"' is not assignable to type 'ReactElement<any, any> | null'.ts(2345)

【问题讨论】:

    标签: reactjs typescript redux react-hooks mobx


    【解决方案1】:

    从架构的角度来看,您的概念可能并不完全正确,因为自定义挂钩应该与数据隔离以可重用

    https://github.com/mobxjs/mobx-react-lite/issues/67

    useDisposable(
      () => mobx.reaction(() => loadingStatusStore.lastRefreshDate,
      refreshDate => {
        // here you can do rest of the `useEffect`, but you need to use that `refreshDate` here,
        // otherwise, MobX won't even bother running it since you are not really using an observed variable.
      }
    )
    

    【讨论】:

    • 好吧,我的用例是有一个自定义钩子来将商店的属性注入n 的组件数。现在,用观察者包装每个组件并在其文件中导入存储并不是一个好主意。此外,自定义的钩子是为了代码的可重用性而制作的,而且这是我在钩子中执行操作并且不想在每个组件中重复它的实际要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2012-09-05
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多