我遇到了一个非常令人沮丧的问题,我不知道发生了什么。我有一个简单的上下文,如下所示:
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
会返回未定义的结果。所以肯定有什么地方出错了,但我很难找到
如有任何帮助,我们将不胜感激!:(
您正在导入AppStateContextProvider
更改import AppStateContext from "../contexts/AppStateContext";
至import { AppStateContext } from "../contexts/AppStateContext";