反应,在使用 useContext 时得到未定义的结果

React, getting undefined as result while using useContext

我试图从 Store 文件中获取 statesetState,但我得到了 undefined。发生了什么,如何解决?

import React, {createContext, useState} from 'react'
import Header from './Header'

export const Data = createContext()


function Store() {
  const [state, setState] = useState(false)
  const  value = {state, setState}

  return (
    <Data.Provider value={value}>
      <Header/>
    </Data.Provider>
  )
}

export default Store
import React, { useContext} from "react";
import { Data } from "./Store";

function Header() {
  const Store = useContext(Data)
  
  console.log(Store) // I get undefined

  return (
    <div>
    </div>
  );
}

export default Header;

您正在创建 Store,但从未调用它,这就是问题所在。将 App 组件包裹在 Store 中,它会起作用。 link here.

的工作示例

index.js:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import Store from "./store";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <Store>
      <App />
    </Store>
  </StrictMode>
);