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

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 返回 undefined。所以某处一定有一些错误,但我正在努力找到它。

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

最佳答案

您正在导入 AppStateContextProvider
更改 import AppStateContext from "../contexts/AppStateContext";
import { AppStateContext } from "../contexts/AppStateContext";

关于javascript - useContext() 返回未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60277899/

10-11 05:57