繁体   English   中英

React 不会将我的 Context 组件视为功能组件。 收到无效挂钩调用错误

[英]React won't acknowledge my Context component as functional component. getting invalid hook call error

我正在处理一个简单的上下文来切换我网站中的抽屉,我正面临这个奇怪的错误,当我试图为我的上下文调用 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)

好的,问题是我正在导入这样的动作函数:

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

虽然我应该像这样导入它:

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

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

暂无
暂无

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

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