尝试在 NextJS 中创建一个井字棋游戏,并尝试创建一个棋盘上下文供我的组件读取。一旦我将一个 reducer 引入到包装器中以实现更复杂的状态,我现在收到一个空错误。
错误:
类型错误:无法读取 null 的属性(读取“useContext”)
终端出错:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
我相信我只在这个项目中安装了 React 版本,接下来使用 create-next-app 时会安装该版本。我很大程度上陷入了在哪里寻找问题所在的困境。在 NextJS 中提供上下文时,我可以不使用 useReducer 钩子(Hook)而不是 useState 钩子(Hook)吗?
上下文声明:
const TTTContext = createContext();
const TTTBoard = new Board(3);
const gameStateReducer = (state, action) => {
switch (action.type) {
//...reducer logic
}
}
const TTTWrapper = ({ children }) => {
const [gameState, dispatch] = useReducer(gameStateReducer, {board: TTTBoard, playerPiece:"DEFAULT"});
const gameContextValue = () => {gameState, dispatch};
return (
<TTTContext.Provider value={gameContextValue}>
{children}
</TTTContext.Provider>
);
}
const useTTTContext = () => {
return useContext(TTTContext)
};
module.exports = { TTTWrapper, useTTTContext }
上下文在 _app.js 中应用:
<TTTWrapper>
<Component {...pageProps} />
</TTTWrapper>
游戏状态在实际的 Grid 组件中检索:
import { useTTTContext } from "../contexts/TTTContext";
const {gameState, dispatch} = useTTTContext();
已解决:const {gameState,dispatch} = useTTTContext();
位于其组件主体之外。
最佳答案
从我所提供的代码来看,问题似乎出在最后一个片段中:
import { useTTTContext } from "../contexts/TTTContext";
const {gameState, dispatch} = useTTTContext();
useTTTContext
似乎没有在任何 React 函数组件主体或任何自定义 React hook 中使用/调用。应将其移至 React 函数或自定义钩子(Hook)主体中。
关于javascript - 在 NextJS 中使用 useContext 和 useReducer 并读取 null 作为上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72252614/