为了账号安全,请及时绑定邮箱和手机立即绑定

反应 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 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信