MOBX 和 React 集成

MOBX and react integration

重新编写客户端应用程序时出现有效挂钩错误...(升级代码)

mobx 6.3.8 mobx react 7.2.1 和 mobx-state-tree 5.0.5 反应 17.0.1 RN 0.64.3

我觉得错误就在这里。我用谷歌搜索了使用商店的代码行,它把我带到了已弃用的网站...我不知道在 https://mobx.js.org/react-integration.html 网站的哪里可以找到新的处理方式...这叫什么?

import { createContext, useContext } from "react"
import { RootStore } from "./root-store"


const RootStoreContext = createContext<RootStore>({} as RootStore)

const RootStoreProvider = RootStoreContext.Provider

// hook error here? // export const useStores = () => useContext(RootStoreContext);

错误: 错误:无效挂钩调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生:

  1. 您的 React 和渲染器版本可能不匹配(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 有关如何调试和修复此问题的提示,请参阅 https://reactjs.org/link/invalid-hook-call

添加更多上下文...根存储文件

import { Instance, SnapshotOut, types } from "mobx-state-tree"

import { creatMediaPlayerModel } from "../../models/media-player"
import { createUserModel } from "../../models/user"
import { createContentModel } from "../../models/content"


export const RootStoreModel = types.model("RootStore", {
mediaPlayerStore: creatMediaPlayerModel(),
userStore: createUserModel(),
contentStore: createContentModel(),
})


export type RootStore = Instance<typeof RootStoreModel>

export type RootStoreSnapshot = SnapshotOut<typeof RootStoreModel>

来自该错误消息:

Hooks can only be called inside of the body of a function component.

您没有从函数组件的主体内部调用挂钩。所以你违反了钩子的规则。

根据 rules of hooks 你只能从 React 函数组件的顶层调用一个钩子。如果您不在功能组件内,则不能使用反应钩子*。

来自文档:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

这意味着您需要从功能组件中调用 useStores

类似于:

function MyComponent() {
  const myStores = useStores()

  // render component with data from stores here
  return <>{myStore.myData}</>
}

* 例外情况是一个可以调用其他挂钩的自定义挂钩。您的 useStores 这里是一个自定义挂钩。因此可以从该自定义挂钩调用 useContext

但是自定义钩子必须遵守与内置钩子相同的使用规则,因此所有钩子都是从函数组件的主体调用的,两者之间只有函数。