在重新撰寫客戶端應用程式時遇到有效的鉤子錯誤...(升級代碼)
mobx 6.3.8 mobx react 7.2.1 和 mobx-state-tree 5.0.5 React 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);
錯誤:錯誤:無效的掛鉤呼叫。鉤子只能在函陣列件的主體內部呼叫。這可能由于以下原因之一而發生:
- 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能違反了 Hooks 規則
- 您可能在同一個應用程式中擁有多個 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>
uj5u.com熱心網友回復:
從該錯誤訊息中:
鉤子只能在函陣列件的主體內部呼叫。
您不是從函陣列件的主體內部呼叫鉤子。所以你打破了鉤子的規則。
根據hooks的規則,你只能從 react 函陣列件的頂層呼叫 hook。如果您不在功能組件內,則不能使用反應鉤子*。
從檔案:
不要在回圈、條件或嵌套函式中呼叫 Hook。相反,在任何提前回傳之前,始終在 React 函式的頂層使用 Hooks。通過遵循此規則,您可以確保每次渲染組件時都以相同的順序呼叫 Hook。這就是允許 React 在多個
useState和useEffect呼叫之間正確保留 Hooks 狀態的原因。
這意味著您需要useStores從功能組件中呼叫。
就像是:
function MyComponent() {
const myStores = useStores()
// render component with data from stores here
return <>{myStore.myData}</>
}
* 例外,有點,是一個可以呼叫其他鉤子的自定義鉤子。你useStores這里是一個自定義鉤子。所以可以useContext從那個自定義鉤子呼叫。
但是那個自定義的鉤子必須遵守與內置鉤子相同的使用規則,所以所有的鉤子都是從一個函陣列件的主體中呼叫的,中間只有一個函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/405753.html
標籤:
下一篇:從類串列陣列中獲取型別
