reactjs 创建上下文未定义

mum43rcc  于 2023-02-18  发布在  React
关注(0)|答案(2)|浏览(190)

当我尝试使用createContext()时,控制台显示以下错误:

App.js:6
Uncaught TypeError: Cannot destructure property 'consoleLogFunction' of '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is null.

我看到其他人在堆栈溢出中对此提出了问题,但我找不到解决方案。

全局上下文. js

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

export const AppContext = createContext();

function GlobalContext() {
    const consoleLogFunction = () => {
        console.log("ok")
    }
    return (
        <AppContext.Provider value={{consoleLogFunction}}></AppContext.Provider>
    )
}

export default GlobalContext

应用程序js

import "./index.css";
import { useContext, useEffect } from "react";
import { AppContext } from "./components/GlobalContext";

function App() {
  const { consoleLogFunction } = useContext(AppContext);
  useEffect(() => {
    consoleLogFunction();
  }, []);

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

export default App;
3b6akqbq

3b6akqbq1#

您不需要导出"AppContext",创建提供程序并导出就足够了。
试试这个,我还做了一些修改,使它更容易使用上下文以后:

全局上下文. js

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

const AppContext = createContext();

function GlobalContext({ children }) {
    const consoleLogFunction = () => {
        console.log("ok")
    }
    return (
      <AppContext.Provider value={{consoleLogFunction}}>
        { children }
      </AppContext.Provider>
    )
}

export default GlobalContext;

// This is a helper
export const useGlobalContext = () => useContext(AppContext);

家. js

import { useEffect } from "react";
import { useGlobalContext } from "./components/GlobalContext";

export const Home = ({ children }) => {
  const { consoleLogFunction } = useGlobalContext();

  useEffect(() => {
    consoleLogFunction();
  }, []);  

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

应用程序js

import "./index.css";
import { useEffect } from "react";
import GlobalContext from "./components/GlobalContext"
import { Home } from "./components/Home";

function App() {
  return(
    <GlobalContext>
      <Home />
    </GlobalContext>
  );
}

export default App;
kqlmhetl

kqlmhetl2#

hello man这个问题是因为App组件没有被 Package 在GlobalContext中.并且在GlobalContext组件中你应该处理children prop .
它将工作时,这样做的例子:

import { useEffect, useContext, createContext } from "react";
import "./styles.css";

export const AppContext = createContext();

function GlobalContext(props) {
  const consoleLogFunction = () => {
    console.log("ok");
  };
  return (
    <AppContext.Provider value={{ consoleLogFunction }}>
      {props.children}
    </AppContext.Provider>
  );
}

const Home = () => {
  const { consoleLogFunction } = useContext(AppContext);
  useEffect(() => {
    consoleLogFunction();
  }, []);

  return <div>home</div>;
};

export default function App() {
  return (
    <GlobalContext>
      <Home />
    </GlobalContext>
  );
}

希望这能有所帮助。

相关问题