[英]React Hooks - Set state based on multiple async calls in loop
我的以下效果是尝试完成以下操作:
不幸的是,我下面的代码似乎不尊重 async / await 并且一旦效果完成运行,我最终得到一个空数组。 有什么想法我可能做错了吗?
useEffect(() => {
const types = ["jobs", "postings", "sale_items"];
async function getEntityReferencesAsync() {
let running_total = [];
types.forEach(
function(type) {
let open = [];
let closed = [];
let therest = [];
const request = await get_data(
`https://myapi.com.com/${type}/${props.id}`
);
response.then(
function(result) {
const result_array = result.data.records;
result_array.forEach(
function(item) {
item["type"] = type;
if (item.status === "open") {
open.push(item);
} else if (item.status === "closed") {
closed.push(item);
} else {
therest.push(item);
}
}.bind(this)
);
running_total = [
...running_total,
...open,
...closed,
...therest
];
}.bind(this)
);
}.bind(this)
);
return running_total;
}
async function getSortedData() {
const sorted_array = await getEntityReferencesAsync();
setEntityReferencesData(sorted_array);
}
getSortedData();
}, [props.id]);
仅供参考,我的 get_data function 看起来像:
async function get_data (endpoint, params) {
if (params === null) {
return await axios.get(endpoint)
} else{
return await axios.get(endpoint, {params: params});
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.