简体   繁体   中英

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

I'm working on a simple context to toggle a drawer in my website and i'm facing this weird error where i'm getting an invalid hook call when trying to call useReducer for my context, i don't understand what's going on as i built multiple context components similar to this before and never faced this problem. what's wrong with my code?

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;

the full error is as follows:

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)

Okay the issue was that i was importing the action function like this:

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

while i should be importing it like this:

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

i don't really understand why but this fixed the issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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