【发布时间】:2020-03-24 16:56:42
【问题描述】:
我正在尝试根据另一个 API 请求的结果发出 API 请求。我让它按照我想要的方式工作,但我不喜欢将 forEach 用于我的 API 调用,我无法思考如何使用不同的方法来完成。有没有关于我如何以更有效的方式做到这一点的建议,例如。与promise.all?
这是我的代码:
api.js
export const fetchOrders = () => {
return fetch(`${url}/work_orders`).then(res => res.json());
};
export const fetchWorker = id => {
return fetch(`${url}/workers/${id}`).then(res => res.json());
};
app.js
function OrderReducer(state, action) {
if (action.type === "fetch") {
return {
orders: [],
error: null,
loading: true
};
} else if (action.type === "success") {
return {
...state,
orders: [
...state.orders,
{
order: action.order,
worker: action.worker
}
],
loading: false
};
} else if (action.type === "error") {
return {
...state,
error: action.message,
loading: false
};
} else {
throw new Error("no action type initialized");
}
}
const Orders = () => {
const [state, dispatch] = React.useReducer(OrderReducer, {
orders: [],
error: null,
loading: true
});
React.useEffect(() => {
dispatch({ type: "fetch" });
fetchOrders()
.then(({ orders }) => {
return orders;
})
.then(orders =>
orders.forEach(order => {
fetchWorker(order.workerId).then(({ worker }) =>
dispatch({ type: "success", order, worker })
);
})
)
.catch(({ message }) => dispatch({ type: "error", message }));
}, []);
存档输出:
orders:[
0: {
order:{...},
worker:{...}
},
...
...
...
20: {
order:{...},
worker:{...}
}
]
【问题讨论】:
-
您可以通过调整您的 api 逻辑,在
fetchOrdersapi 中为每个订单从 api 端获取工人详细信息,如果 api 是您制作的。
标签: javascript reactjs api react-hooks