繁体   English   中英

在 NextJS 中使用 useContext 和 useReducer 并将 null 作为上下文读取

[英]Using useContext and useReducer in NextJS and reading null as context

尝试在 NextJS 中创建井字游戏,并尝试为我的组件创建棋盘上下文以供阅读。 一旦我在 Wrapper 中引入了一个 reducer 以获得更复杂的状态,我现在就会收到一个 null 错误。 错误: TypeError: Cannot read properties of null (reading 'useContext')

然后终端出错:

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

  1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 你可能在同一个应用程序中拥有多个 React 副本

我相信我只在这个项目中安装了 react 版本,下次使用 create-next-app 时安装。 我在很大程度上被困在哪里寻找问题所在。 在 NextJS 中提供上下文时,我可以不使用 useReducer 挂钩而不是 useState 挂钩吗?

上下文声明:

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 挂钩中使用/调用。 它应该被移动到 React 函数或自定义钩子体中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM