Axios 和循环承诺

Axios and looped promises

我在轴 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(getNeededData只是选择参数):

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),但我有 first、second、first、second、first 和 this 在一个循环中。 为什么它一直这样工作? 我可以更改什么来解决这个问题?

通过将 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
    });
}, []);