我不断收到无效挂钩调用错误

I keep getting an invalid hook call error

我在处理我的项目时不断收到无效的钩子调用错误,这是我唯一使用的钩子,我只在这两个地方使用它,我的导师不明白我为什么得到这个错误。我完全不知所措,我不知道如何前进,因为我的应用程序需要使用上下文。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { FoodProvider } from './FoodContext';
import { BrowserRouter as Router } from 'react-router-dom'

ReactDOM.render(
  <Router>
    <FoodProvider>
      <App />
    </FoodProvider>
   </Router>,
  document.getElementById('root')
);

...

import logo from './logo.svg';
import './App.css';
import Navbar from './Navbar';

function App() {
  return (
    <div className="App">
      <Navbar/>
    </div>
  );
}

export default App;

...

import React from 'react'
export default function Navbar() {
    return (
        <div className="navbar">
            <div className="nav-head">
                <h1>Meals <span>App</span></h1>
            </div>
            <div className="nav-links">
                <ul>
                    <li>Home</li>
                    <li>Catagories</li>
                    <li>Random</li>
                </ul>
            </div>
        </div>
    )
}

...

import React,{useContext} from "react";

const FoodContext = useContext()

function FoodProvider(props){
    return(
        <FoodContext.Provider value =''>
            {props.children}
        </FoodContext.Provider>
    )

}


export {FoodContext, FoodProvider}

您错误地使用了 useContext 挂钩而不是 createContext 函数。

import { createContext, useContext } from 'react';

// Create a React Context
const FoodContext = createContext(/* set any default value here */);

// Create a custom hook
const useFoodContext = () => useContext(FoodContext);

// Create Provider component
function FoodProvider({ children }) {
  return(
    <FoodContext.Provider value={/* pass a context value here */}>
      {children}
    </FoodContext.Provider>
  );
}

export { FoodContext, useFoodContext };
export default FoodProvider;

...

import FoodProvider from './FoodContext';
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <Router>
    <FoodProvider>
      <App />
    </FoodProvider>
   </Router>,
  document.getElementById('root')
);