首页 > 解决方案 > 从类别 API 获取完成后从产品 API 获取?

问题描述

我在我的应用程序中遇到了一个问题,即在我更新我的状态之前调用我的 api(我知道更新状态是一种async行为,所以我使用了then)但这不起作用。应用程序的工作方式是首先我从一个类别中获取我的类别,api然后我根据所选类别调用第二个api类别(如果没有选择我会显示所有产品,但如果选择了一些我会根据它们显示产品)。所以这是我的实现:

const [CompanyCategories, setCompanyCategories] = useState({ loading: true, categories: [] });
  const [companyProducts, setCompanyProducts] = useState([]);

  const fetchCategories = useCallback(() => {
    return fetch(`***Categories API***`)
      .then(res => {
        if (!res.ok) {
          throw new Error('Failed to fetch.');
        }
        return res.json()
      })
      .then(data => {
        setCompanyCategories({
          loading: false, categories: data.map((el, index) => {
            return {
              id: el.id,
              title: el.title,
              selected: false
            }
          })
        })
      })
      .catch(err => {
        console.log(err);
      });

  }, []);

  const fetchCompanyProducts = (companyId, selectedCats) => {
    axios
      .post('***Products API***', {
        "companyID": companyId,
        "groupOfCategory": selectedCats
      })
      .then(response => {
        // response.data is the products
        const products = response.data
        console.log('this is products' ,products)
      })
      .catch(error => {
        // error.message is the error message
        console.log(error.message)
      })
  }

  const fetchProductsHandler = () => {
    const selectedCategoriesId = CompanyCategories.categories.filter(el => el.selected).map(el => el.id);
    console.log('selected : ' , CompanyCategories.categories) // its empty array [] but it has to be [7,8,10,11] these are selected categories IDs which for none selected I'll send all as selected to backend.
    if (selectedCategoriesId.length == 0) {
      fetchCompanyProducts(companyId, CompanyCategories.categories.map((el, index) => el.id))
    } else {
      fetchCompanyProducts(companyId, selectedCategoriesId)
    }
  }

  const onRadioBtnClick = (item) => {
    let updatedState = CompanyCategories.categories.map((el) => {
      if (el.id == item.id) {
        return {
          ...el,
          selected: !el.selected
        }
      } else {
        return {
          ...el,
          selected: el.selected
        }
      }
    });
    setCompanyCategories({ loading: false, categories: updatedState })
  };

  useEffect(() => {
    fetchCategories()
    .then(() => {  //here I use then so after categories state updated, I call products
      fetchProductsHandler()
    })
  }, [])

我面临的是我成功获得了类别,但是在我的状态更新之前调用了第二个 API,因此 products 函数的第二个参数是一个不应该的空数组。那么我该如何解决呢?

标签: reactjsreactn

解决方案


如果我理解你的问题是正确的:

您希望在类别确定后获取产品,您可以使用 useEffect 挂钩轻松实现此目的,并等待类别值更改

  useEffect(() => {
    fetchCategories()
  }, []);

  useEffect(() => {
      if(!CompanyCategories.loading) fetchProductsHandler()
  }, [CompanyCategories]);

推荐阅读