javascript 无法使用React上下文内的值

ulmd4ohb  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(145)

我在网页中设置用户时遇到问题。我使用AppContext,所有组件都在其中更新状态。当我运行代码时,它说setUserundefined,但我在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)
    }
}
lnlaulya

lnlaulya1#

您只能在provider中嵌入的组件中访问context中的变量和函数。为了实现您的目的,请将App组件放在AppProvider中。例如,您可以在index文件中这样做:

ReactDOM.render(
  <React.StrictMode>
    <AppProvider> 
      <App /> 
    </AppProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

而且您不需要在return中包含<AppContext />

相关问题