reactjs - 从类别 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 函数的第二个参数是一个不应该的空数组。那么我该如何解决呢?
解决方案
如果我理解你的问题是正确的:
您希望在类别确定后获取产品,您可以使用 useEffect 挂钩轻松实现此目的,并等待类别值更改
useEffect(() => {
fetchCategories()
}, []);
useEffect(() => {
if(!CompanyCategories.loading) fetchProductsHandler()
}, [CompanyCategories]);
推荐阅读
- java - 我们如何将字符串数组值与字符串进行比较?(爪哇)
- javascript - mat-datepicker 使应用程序崩溃而没有记录错误
- javascript - Vue.js - 具有多个同名键的绑定数组
- python - 使用 Keras 理解多元时间序列分类
- clang - 如何使用 Clang 将 OpenCL 内核编译为 SPIR-V
- javascript - Javascript 异步问题 (Sharepoint)
- c# - C# - 对象结果的反序列化并将其映射到 Web API 列表
- opengl - 何时在体数据中应用 phong 着色?
- java - 给出输入时打印程序的星期几?
- java - 创建 Java URL 时需要转义“%”