微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React JS:如何在自定义钩子中使用观察者获取MobX存储的状态? 用例:代码:打字稿错误:

如何解决React JS:如何在自定义钩子中使用观察者获取MobX存储的状态? 用例:代码:打字稿错误:

用例:

我有一个自定义钩子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)

解决方法

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

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.
  }
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。