【发布时间】:2021-06-16 11:59:26
【问题描述】:
我有一个 id 的数组,例如 [123,345,212,232……] 我有一个 Rest API 可以根据 id 响应特定产品。
那么在 ReactJS 中,我将如何遍历数组并获取产品并存储在状态中
我尝试在 useEffect{running once as in componentDidMount} 中执行此操作,但它只将第一个产品存储在数组中。
有没有更好的方法来做到这一点?
我有问题的实际代码是
useEffect(() => {
const getBought = async () => {
user.bought.map(async (boughtID) => {
let bought = await get(`/bought/${boughtID}`, {}, true);
let boughtDate = bought.createdAt.slice(0, 10);
bought.products.map(async (pr) => {
let product = await get(`product/${pr.product}`);
let quantityBought = pr.quantity;
setAllBoughts({
...allBoughts,
[boughtDate]: [
...(allBoughts.boughtDate || []),
{
product,
quantityBought,
},
],
});
});
});
};
getBought();
}, []);
所以我有一个用户,在购买的密钥中有一组购买的 ID...
所以我正在遍历那些购买的钥匙
购买的架构中的产品具有产品 ID 和购买的产品数量(pr.product 和 pr.quantity)。所以我点击 API,并将所有产品保存在状态对象中。
所以 allBoughts 是状态,它是一个对象,其键为(日期),如代码 .createdAt.slice(0,10) 中所示,它为我提供了删除 mongodb 添加的其余内容的日期。
但每次我这样做时,都会发生一些事情。
要么只保存第一项,其余不保存 相同的项目被覆盖 或者页面无限重新加载(尤其是当我尝试从 useEffect 中删除依赖数组时)
【问题讨论】:
-
I tried doing this in useEffect{running once as in componentDidMount} but it only stores the first product in array.这听起来是正确的方法,它只是有一个错误。请向我们展示您为此编写的代码 -
你能看到我的代码吗,我已经编辑了帖子
标签: node.js reactjs api express