简体   繁体   English

React Context 没有定义 no-undef

[英]React Context is not defined no-undef

I have navigation constant which is an array of objects(web-store mega-nav).我有导航常量,它是一个对象数组(网络商店巨型导航)。 I need to use context provider and when I'm trying to use my context it's telling me NavContext' is not defined no-undef .我需要使用上下文提供程序,当我尝试使用我的上下文时,它告诉我NavContext' is not defined no-undef

NavContext.js导航上下文.js

import { createContext } from 'react'

const navigation = [...] // array of objects

const NavContext = createContext(navigation)

export default NavContext

Nav.js导航.js

import {createContext} from 'react'
import NavContext from './context/NavContext' //added

function Nav() {

    return (
        <NavContext.Provider> //deleted value
        // childrens
        </NavContext.Provider>
    )
}

Sidebar.js Sidebar.js

//then in one of the child I'm trying to call it:

import { useContext } from 'react'
import NavContext from '../context/NavContext' //added

function Sidebar(){
    const nav = useContext(NavContext)

    return (
        {nav.map(...)} // nav is undefined
    )
}

Now nav constant is undefined when I'm using useContext现在,当我使用useContext时,导航常量未定义

For my knowledge, you have to import useContext like this.据我所知,您必须像这样导入useContext

import React, { useContext } from 'react'

You need to export the create context like this您需要像这样导出创建上下文

export const NavContext = createContext(navigation)导出 const NavContext = createContext(navigation)

Then import it into your child component like this然后像这样将它导入到您的子组件中

import { NavContext} from "../Nav";从“../Nav”导入{ NavContext};

//Create a new NavContext.js File. //创建一个新的 NavContext.js 文件。

 import React, { createContext, useReducer } from "react"; export const NavContext = createContext(); const initialState = { } function reducer(state, action) { return {...state, ...action }; } export const NavProvider = (props) => { const [state, dispatch] = useReducer(reducer, initialState); return ( <NavContext.Provider value={{ state, dispatch }}> {props.children} </NavContext.Provider> ); };

Then in your index.js file.然后在你的 index.js 文件中。

 import { NavProvider} from "./NavContext"; ReactDOM.render( <NavProvider> <App /> </NavProvider>, document.getElementById("root") );

If that doesnt work idk what will.如果那不起作用,我会怎么做。

Try not to pass any arguments into createContext, then pass navigation into Context provider as prop尽量不要将任何 arguments 传递给 createContext,然后将导航作为道具传递给上下文提供程序

<Context.Provider value={navigation} />

And then get the value using useContext Hook in your consumer component然后在消费者组件中使用 useContext Hook 获取值

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

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