gpt4 book ai didi

javascript - useContext() 返回未定义

转载 作者:行者123 更新时间:2023-12-01 00:07:30 28 4
gpt4 key购买 nike

我遇到了一个非常令人沮丧的问题,我不知道发生了什么。我有一个简单的上下文,如下所示:

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

更改从“../contexts/AppStateContext”导入AppStateContext;

从“../contexts/AppStateContext”导入{AppStateContext};

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com