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

标签 javascript reactjs react-hooks next.js

尝试在 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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. 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/

相关文章:

node.js - 在 Jenkins 中构建成功,但 AWS-Codebuild 出现插件错误

css - (S)CSS React 元素选择器

javascript - 如何在 React 中删除包含子组件的功能性内存组件的渲染器?

javascript - 如何通过 html "JS file"调用 "button-click"并且 JS 文件正在使用 shell.js 运行 bash 脚本

javascript - 你如何监听在 JavaScript 中移动的 HTML 元素?

javascript - 从 cmd 停止 npm

javascript - 映射关联数组的值

javascript - React - Axios 向用户显示消息

javascript - React 错误边界不适用于 React

javascript - 如何使用 AJAX 将变量传递给 PHP?