Axios和循环承诺



我对轴上的循环GET请求有问题,我不明白为什么。

const [ state, setState ] = useState<any[]>([]);
ids.forEach((id) => {
getData(id)
.then((smth: Map<string, any>[]) => getNeededData(smth, id));
});
console.log(JSON.stringify(state));

和getData(getNeedData只是选择参数(:

export const getData= async (id: string) => {
const response = await Axios.get(`/rest/${id}`)
.then((res: { data: any; }) => res.data);
return response;
};

我应该有2个响应(变量"ids"中有2个id(,但我在循环中有第一个、第二个、第一、第二、第一和这个。为什么它一直这样工作?我能改变什么来解决这个问题?

通过将forEach放在组件函数的顶层,每当React调用函数以呈现其内容时,React都会运行它。您显示的代码没有设置状态,但我假设您的真实代码设置了状态。

要仅在组件首次装载时执行此操作,请将其封装在具有空依赖数组的useEffect回调中:

const [ state, setState ] = useState<any[]>([]);
useEffect(() => {
ids.forEach((id) => {
getData(id)
.then(/*...*/);
});
}, []);

如果所有的结果都在state数组中,那么您可能希望使用mapPromise.all将它们聚集在一起,并对它们进行单个状态更改,例如:

const [ state, setState ] = useState<any[]>([]);
useEffect(() => {
Promise.all(
ids.map((id) => {
return getData(id).then(/*...*/);
})
)
.then(allResults => {
// Use `allResults` to set state; it will be an array in the same order
// that the `id` array was in
})
.catch(error => {
// handle/report error
});
}, []);

最新更新