useContext() 返回未定义

IT技术 javascript reactjs undefined react-hooks
2021-03-24 07:29:34

我遇到了一个非常令人沮丧的问题,我无法弄清楚发生了什么。我有一个简单的上下文,如下所示:

import React, { useState, createContext } from "react";

export const AppStateContext = createContext();

const AppStateContextProvider = props => {
  const [appState, setAppState] = useState({
    cartOpen: false
  });

  return <AppStateContext.Provider value={{ appState, setAppState }}>{props.children}</AppStateContext.Provider>;
};

export default AppStateContextProvider;

我还将我的应用程序包装在提供程序中:

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import CssBaseline from "@material-ui/core/CssBaseline";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
import { deepPurple, amber } from "@material-ui/core/colors";
import AppStateContextProvider from "./contexts/AppStateContext";

const theme = createMuiTheme({
  palette: {
    type: "dark",
    primary: {
      main: deepPurple[400]
    },
    secondary: {
      main: amber[800]
    }
  }
});

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <AppStateContextProvider>
      <App />
    </AppStateContextProvider>
  </ThemeProvider>,
  document.getElementById("root")
);

我在这里使用上下文:

import React, { useContext } from "react";
import {
  Grid,
  Card,
  CardHeader,
  CardContent,
  CardActions,
  Divider,
  Container,
  AppBar,
  Toolbar,
  IconButton,
  Tooltip
} from "@material-ui/core";
import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";
import AppStateContext from "../contexts/AppStateContext";

const TopAppBar = props => {
  console.log("context: ", AppStateContext);
  console.log("useContext(context): ", useContext(AppStateContext));

  //   const { appState, setAppState } = useContext(AppStateContext);

  return (
      <AppBar>
      <Toolbar>
        <Tooltip title="View Cart">
          <IconButton>
            <ShoppingCartIcon />
          </IconButton>
        </Tooltip>
      </Toolbar>
    </AppBar>
  );
};

export default TopAppBar;

被注释掉的代码行会引发错误,因为useContext(AppStateContext)undefined两个控制台日志的输出是这样的:

context:  props => {
  const [appState, setAppState] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])({
    cartOpen: false
  });
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(App…
useContext(context):  undefined

如您所见,上下文看起来不错,但调用useContext上下文返回未定义。所以一定有什么地方有错误,但我正在努力找到它。

任何帮助将不胜感激!:)

1个回答

您正在进口 AppStateContextProvider

改变 import AppStateContext from "../contexts/AppStateContext";

import { AppStateContext } from "../contexts/AppStateContext";