React Context 未定义 no-undef

Mor*_*ani 2 javascript reactjs

我有导航常量,它是一个对象数组(网络商店大型导航)。我需要使用上下文提供程序,当我尝试使用上下文时,它会告诉我NavContext' is not defined no-undef

NavContext.js

import { createContext } from 'react'

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

const NavContext = createContext(navigation)

export default NavContext
Run Code Online (Sandbox Code Playgroud)

导航js

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

function Nav() {

    return (
        <NavContext.Provider> //deleted value
        // childrens
        </NavContext.Provider>
    )
}
Run Code Online (Sandbox Code Playgroud)

侧边栏.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
    )
}
Run Code Online (Sandbox Code Playgroud)

现在,当我使用时,导航常量未定义useContext

two*_*nds 5

您需要像这样导出创建上下文

导出 const NavContext = createContext(导航)

然后将其导入到您的子组件中,如下所示

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