我在网页中设置用户时遇到问题。我使用AppContext
,所有组件都在其中更新状态。当我运行代码时,它说setUser
是undefined
,但我在AppContext
中定义了它,并导入到App.jsx
中。有人能帮忙吗?我看到其他解决方案,似乎
const { setUser } = useContext(AppContext);
必须在组件之外,但显示以下错误:
TypeError: Cannot destructure property 'setUser' of 'Object(...)(...)' as it is undefined.
App
D:/ELEARNING/PROYECTS/PROYECT-ANDREA/store-lopez-andrea/src/App.js:11
8 | import { Router } from "./routers/Router";
9 |
10 | function App() {
> 11 | const { setUser } = useContext(AppContext);
12 | useEffect(() => {
13 | getUser().then((user) => {
14 | setUser(user);
这是App.jsx:
import "./App.css";
import { Header } from "./components/header/Header";
import { Nav } from "./components/nav/Nav.jsx";
import { getUser } from "./services/users";
import { AppContext } from "./context/AppContext";
import { Notification } from "./components/notification/Notification";
import { Router } from "./routers/Router";
function App() {
const { setUser } = useContext(AppContext);
useEffect(() => {
getUser().then((user) => {
setUser(user);
});
}, [setUser]);
return (
<div>
<Notification />
<Nav />
<Header />
<Router />
<AppContext />
</div>
);
}
export default App;
这是AppContext.jsx:
import React,{ useState } from "react";
import { usePagination } from "../components/utils/pagination.jsx";
export const AppContext = React.createContext();
export default function AppProvider({ children }) {
const [user,setUser] = useState({})
const [points, setPoints] = useState(0)
const [products, setProducts] = useState([])
const [reedemStatus, setReedemStatus] = useState({})
const [history, setHistory] = useState([])
const paginationList = usePagination(products, 16)
const paginationHistoryList = usePagination(history, 16)
const totalProducts = products.length
const totalHistory = history.length
const handlerAddPoint =(value)=>{
const newUser = {...user}
newUser.points = user.points + value
setUser(newUser)
}
const handlerSubtractPoint =(points)=>{
const newUser = {...user}
newUser.points = user.points - points
setUser(newUser)
}
return(
<AppContext.Provider value={{user,
setUser,
handlerAddPoint,
handlerSubtractPoint,
points,
setPoints,
products,
setProducts,
totalProducts,
paginationList,
reedemStatus,
setReedemStatus,
history,
setHistory,
paginationHistoryList,
totalHistory}}>
{children}
</AppContext.Provider>
);
}
在Users.jsx中,我有“getUser”组件
import {BASE_URL, headers} from "./constant"
export const getUser = async()=>{
try{
const response= await fetch(BASE_URL+"user/me",{headers})
const data = await response.json()
return data
} catch (error){
console.log(error)
}
}
1条答案
按热度按时间lnlaulya1#
您只能在
provider
中嵌入的组件中访问context
中的变量和函数。为了实现您的目的,请将App
组件放在AppProvider
中。例如,您可以在index
文件中这样做:而且您不需要在
return
中包含<AppContext />
。