开发者问题收集

为什么 useContext 返回 undefined?

2022-07-03
97

我遇到一个问题,即 useContext 返回 undefined 值。

我为折叠菜单(如切换菜单)创建了一个上下文。之后,我将提供程序添加到索引文件中以包装主组件。我转到主文件导入 CollapseContext ,但这是文件,它不起作用 :( ?

我不明白为什么它返回 undefined

下面是我的代码。

src/context/CollapseMenuContext.js

import React, { createContext, useState } from 'react'

export const CollapseContext = createContext()

export default function CollapseProvider({ children }) {
  const [isCollapse, setIsCollapse] = useState(false)

  const toggleCollapse = () => {
    setIsCollapse(!isCollapse)
  }

  const values = {
    isCollapse,
    toggleCollapse,
  }

  return <CollapseContext.Provider value={values}>{children}</CollapseContext.Provider>
}

src/app/index.jsx

import React from 'react'
import Header from '_components/Header'
import CollapseProvider from '../context/CollapseMenuContext.js'
import MainDigistallDesktop from './Main'

function DigistallDesktop() {
  return (
    <CollapseProvider>
      <Header />
      <section className='section-content section-content--top mains-screen pb-0' id='checkHeight'>
        <MainDigistallDesktop />
      </section>
    </CollapseProvider>
  )
}

export default DigistallDesktop

src/app/Main.jsx

import React, { useContext } from 'react'
import { Route, Switch } from 'react-router-dom'
import OrderRecord from './OrderRecord'
import Sidebar from './components/Sidebar/index'
import Dashboard from './Dashboard'
import Delivery from './Delivery'
import Products from './Products'
import Setting from './Setting'
import { CollapseContext } from '../context/CollapseMenuContext.js'

function MainDigistallDesktop() {
  const context = useContext(CollapseContext)
  console.info(context)
  return (
    <div className='container-fluid' style={{ minWidth: '1200px' }}>
      <div className='row'>
        {/* <div className={`${isCollapse ? 'col-1' : 'col-2'} position-relative`}>
          <Sidebar />
        </div> */}
        <div className='col-10 mx-auto'>
          <Switch>
            <Route path='/' exact component={Dashboard} />
            <Route path='/order-records' exact component={OrderRecord} />
            <Route path='/delivery' exact component={Delivery} />
            <Route path='/products' exact component={Products} />
            <Route path='/setting' exact component={Setting} />
          </Switch>
        </div>
      </div>
    </div>
  )
}

export default MainDigistallDesktop

结果: 在此处输入图像描述

编辑 1: 这是根应用程序文件:

export default function App() {
  if (process.env.REACT_APP_ENVIRONMENT === 'production') useScript()

  return (
    <Provider store={store}>
      <ToastProvider>
        <FirebaseContext.Provider value={{ firebase }}>
          <Router history={history}>
            <Switch>
              <Route path='/sign-in' exact={true} component={SignInPage} />
              <Route path='/sign-up' exact={true} component={SignUpPage} />
              <Route path='/reset-password' exact={true} component={ForgotPasswordPage} />
              <Route path='/reset-password-with-code' component={ResetPasswordPage} />
              <Route path='/info' exact={true} component={RedirectGoogleSites} />
              <Route path='/policy' exact={true} component={Policy} />
              <ProtectedRoute path='/welcome' exact={true} component={Welcome} />
              <ProtectedRoute path='/digistall' component={Digistall} /> --> this is index.jsx file
              {/* <ProtectedRoute path='/' component={MainPage} /> */}
              <ProtectedRoute path='/' component={MainDigistallDesktop} /> --> lead to my app current (Main.jsx)
            </Switch>
          </Router>
        </FirebaseContext.Provider>
      </ToastProvider>
    </Provider>
  )
}
1个回答

编辑:您需要将 CollapseProviderMainDigistallDesktop 包装在您的应用组件中:

return (
    <Provider store={store}>
        <ToastProvider>
            <FirebaseContext.Provider value={{ firebase }}>
            <Router history={history}>
                <Switch>
                <Route path='/sign-in' exact={true} component={SignInPage} />
                <Route path='/sign-up' exact={true} component={SignUpPage} />
                <Route path='/reset-password' exact={true} component={ForgotPasswordPage} />
                <Route path='/reset-password-with-code' component={ResetPasswordPage} />
                <Route path='/info' exact={true} component={RedirectGoogleSites} />
                <Route path='/policy' exact={true} component={Policy} />
                <ProtectedRoute path='/welcome' exact={true} component={Welcome} />
                <ProtectedRoute path='/digistall' component={Digistall} /> --> this is index.jsx file
                {/* <ProtectedRoute path='/' component={MainPage} /> */}


                <ProtectedRoute path='/' render={() => (
                    <CollapseProvider>
                        <MainDigistallDesktop/>
                    </CollapseProvider>
                )} /> --> lead to my app current (Main.jsx)


                </Switch>
            </Router>
            </FirebaseContext.Provider>
        </ToastProvider>
    </Provider>
)
Aidin53
2022-07-03