如何执行多个获取请求

sal*_*ax1 5 javascript reactjs fetch-api promise.all

我想使用 React/JavaScript 执行多个获取请求,我进行了以下尝试,该尝试有效:

const fetchAll = async () => {
    Promise.all([
        await fetch('/api/...'),
        await fetch('/api/...')
    ]).then(links => {
        const response1 = links[0];
        const response2 = links[1];

        timeData = response1.json();
        functionData = response2.json();
    })
}
Run Code Online (Sandbox Code Playgroud)

但我想这样做,因为这似乎更有用。如果可能的话,我想使用 useEffect 和 useState 并将不同 API 的数据加载到 useState 中的不同数组中。这是一个例子:

const [data, setData] = useState([]);
useEffect(() => {
        fetch("/api/..")
            .then((response) => response.json())
            .then((r) => {
                setData(r);
            });
    }, []);
Run Code Online (Sandbox Code Playgroud)

有没有办法对多个请求执行此操作并将数据保存在不同的数组中,以便我以后可以访问它们?

Phi*_*hil 2

这可以很好地完成

  1. 创建要解析的 URL 数组
  2. 迭代返回的数组数据
  3. 将这些数据传递给您的设置器

例如,在某个模块中创建一些辅助函数

// fetch-helpers.js

// performs a request and resolves with JSON
export const fetchJson = async (url, init = {}) => {
  const res = await fetch(url, init);
  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`);
  }
  return res.json();
};

// get JSON from multiple URLs and pass to setters
export const fetchAndSetAll = async (collection) => {
  // fetch all data first
  const allData = await Promise.all(
    collection.map(({ url, init }) => fetchJson(url, init))
  );

  // iterate setters and pass in data
  collection.forEach(({ setter }, i) => {
    setter(allData[i]);
  });
};
Run Code Online (Sandbox Code Playgroud)

在你的组件中......

import { useEffect, useState } from "react";
import { fetchAndSetAll } from "./fetch-helpers";

export const MyComponent = () => {
  // initialise state to match the API response data types
  const [timeData, setTimeData] = useState([]);
  const [functionData, setFunctionData] = useState([]);

  useEffect(() => {
    fetchAndSetAll([
      {
        url: "/api/...",
        setter: setTimeData,
      },
      {
        url: "/api/...",
        setter: setFunctionData,
      },
    ]).catch(console.error);
  }, []);

  return <>{/* ... */}</>;
};
Run Code Online (Sandbox Code Playgroud)