亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反應 useContext() 返回未定義

反應 useContext() 返回未定義

泛舟湖上清波郎朗 2022-11-11 13:44:31
我的上下文提供程序有這個代碼,我有我的組件,但是當我嘗試使用 useProductState 或 useProductDispatch 在孩子中使用它時,它返回未定義(拋出錯誤);import React from "react";import productsReducer from "./productsReducer";const ProductsStateContext = React.createContext();const ProductsDispatchContext = React.createContext();const initialState = {  restaurantTitle: "",  restaurantId: "VljSa5Eakepw9QkTAUOW",  productsCollection: "",  categories: [],  defaultCategory: "",  isLoading: true,};function ProductsProvider({ children }) {  const [state, dispatch] = React.useReducer(productsReducer, initialState);  return (    <ProductsStateContext.Provider value={state}>      <ProductsDispatchContext.Provider value={dispatch}>        {children}      </ProductsDispatchContext.Provider>    </ProductsStateContext.Provider>  );}function useProductsState() {  const context = React.useContext(ProductsStateContext);  if (context === undefined) {    throw new Error("useProductsState must be used within a ProductsProvider");  }  return context;}function useProductsDispatch() {  const context = React.useContext(ProductsDispatchContext);  if (context === undefined) {    throw new Error(      "useProductsDispatch must be used within a ProductsProvider"    );  }  return context;}export { ProductsProvider, useProductsState, useProductsDispatch };有人可以解釋這是如何工作的嗎,我正在嘗試訪問狀態并分派到一個功能組件中,該組件是 .
查看完整描述

1 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

您應該等待回復fetchRestaurantData:


const fetchRestaurantData = async (state, value) => {  // add async keyword to the function 

  let newState = state;

  return await axios  // here add await 

    .post(api.routes.restaurant, { restaurantId: state.restaurantId })

    .then((res) => {

      newState.restaurantTitle = res.data.restaurantTitle;


      res.data.categories.forEach(

        (category) =>

          (newState.categories[category] = {

            loaded: false,

            props: [],

          })

      );

      newState.defaultCategory = res.data.categories[0];

      newState.productsCollection = res.data.productsCollection;

      newState.isLoading = false;


      return axios.post(api.routes.category, {

        productsCollection: res.data.productsCollection,

        categoryId: newState.defaultCategory,

      });

    })

    .then((res) => {

      newState.categories[newState.defaultCategory].props =

        res.data[newState.defaultCategory];

      newState.categories[newState.defaultCategory].loaded = true;

      console.log(newState);

      return newState;

    });

};


查看完整回答
反對 回復 2022-11-11
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號