javascript React不会将我的Context组件确认为功能组件,获取无效的钩子调用错误

eqoofvh9  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(75)

我正在使用一个简单的上下文来切换我的网站中的抽屉,我遇到了这个奇怪的错误,当我试图调用useReducer为我的上下文时,我得到了一个无效的钩子调用,我不明白发生了什么,因为我以前构建了多个类似的上下文组件,从来没有遇到过这个问题。我的代码有什么问题?

import React from 'react';
import { useReducer } from 'react';

export const DrawerContext = React.createContext();

export function toggleDrawerDisplayAction(dispatch, currentDrawerState) {
    if (currentDrawerState == "none") {
        dispatch({ type: "SHOW_DRAWER", payload: "block" });
    } else {
        dispatch({ type: "HIDE_DRAWER", payload: "none" });
    }
}

export function HideDrawerAction(dispatch) {
    dispatch({ type: "HIDE_DRAWER", payload: "none" });
}

export function drawerReducer(state, action) {
    console.log(action);
    switch (action.type) {
        case "SHOW_DRAWER":
            return { currentDrawerState: action.payload };
        case "HIDE_DRAWER":
            return { currentDrawerState: action.payload };
        default:
            return { currentDrawerState: state };
    }
}

let DrawerContextProvider = function (props) {
    const [state, dispatch] = useReducer(drawerReducer, {
        currentDrawerState: "none"
    })

    return (<DrawerContext.Provider value={{ ...state, dispatch }}>
        {props.children}
    </DrawerContext.Provider>
    )
}

export default DrawerContextProvider;

全部误差如下:

react-dom.development.js:16227 Uncaught Error: 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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at Object.throwInvalidHookError (react-dom.development.js:16227:1)
    at useReducer (react.development.js:1626:1)
bwitn5fc

bwitn5fc1#

好吧,问题是我导入的action函数是这样的:

import toggleDrawerDisplayAction from "../contexts/DrawerContext";

虽然我应该这样导入它:

import {toggleDrawerDisplayAction} from "../contexts/DrawerContext";

我真的不明白为什么,但这解决了问题

相关问题