繁体   English   中英

反应 useContext() 返回未定义

[英]React useContext() returns undefined

我的上下文提供程序有这个代码,我有我的组件,但是当我尝试使用 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 };

有人可以解释这是如何工作的吗,我正在尝试访问 state 并分派到一个子功能组件中。

更新:

我有这个作为我的减速器的一个动作

case "FETCH_RESTAURANT_DATA": {
      return fetchRestaurantData(state, action.payload);
    }

Function 机身如下:

const fetchRestaurantData = (state, value) => {
  let newState = state;
  return axios
    .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;
    });
};

我认为正在发生的事情,我认为在减速器中它不会等待我的响应并使用未定义的值更新上下文 state 然后触发我的错误。

我试图制作一个中间异步 function 等待 fetchRestaurantData() 响应,但在得到响应之前它仍在更新

您应该等待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;
    });
};

有关异步函数的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM