【问题标题】:Axios and looped promisesAxios 和循环承诺
【发布时间】:2021-09-07 05:18:26
【问题描述】:

我对轴 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),但我有第一个、第二个、第一个、第二个、第一个,并且 this 在一个循环中。 为什么它一直这样工作? 我可以改变什么来解决这个问题?

【问题讨论】:

  • 您希望这些请求串行执行还是并行执行?
  • 最多5个请求,所以差别不大,但我很好奇,如何在串行和并行之间切换? :)

标签: reactjs typescript promise axios


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2017-12-18
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2020-08-16
    • 2019-06-17
    • 2015-12-18
    相关资源
    最近更新 更多