在功能组件中使用 MobX @inject with Context API

Use MobX @inject with Context API in functional components

我如何在功能性子组件中实现@inject 和观察者,而无需显式导入带有上下文的存储并对其进行解构。下面的回购和部署网站

https://laughing-mayer-7a7c36.netlify.app/

https://github.com/hildakh/testmobx

你可以像那样做钩子,所以你不需要每次都导入上下文,只需要这个钩子:

export const useStore = () => {
  const store = React.useContext(storeContext)
  if (!store) {
    // this is especially useful in TypeScript so you don't need to be checking for null all the time
    throw new Error('useStore must be used within a StoreProvider.')
  }
  return store
}

如果您愿意,您仍然可以将 inject 装饰器与功能组件一起使用,它仍然有效,而且是完全好的方式