如何执行多个提取请求

发布于 2025-02-07 03:15:34 字数 751 浏览 2 评论 0 原文

我想对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();
    })
}

但是我想这样做,因为这似乎更有用。如果可能的话,我想在USESTATE中使用使用效率和使用情况并加载不同阵列中不同API的数据。这是一个示例:

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

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

I would like to do multiple fetch requests with React/JavaScript, I have the following attempt which kind of works:

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();
    })
}

But I would like to do it this way, because that seems more useful. I would like to use useEffect and useState and load the data of the different APIs in different arrays in useState if that's possible. Here is an example:

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

Is there a way to do this for multiple requests and save the data in different arrays so I can access them later on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

如何视而不见 2025-02-14 03:15:34

如果我正确理解您的问题,那么我认为您想要这样的东西:

const [resp1, setResp1] = useState();
const [resp2, setResp2] = useState();

useEffect(() => {
    Promise.all([
        fetch('/api/...'),
        fetch('/api/...')
    ]).then(links => {
        const response1 = links[0];
        const response2 = links[1];
        
        setResp1(response1);
        setResp2(response2);
    })
}, [/*dependency array*/])

在这里,我们利用 useffect 使您的同时 fetch es eS;我们真的不需要也不需要使用等待,因为我们希望它们同时运行,并且 Promise.All 才能在数组中的所有承诺解决时才能解决。在。您的组件。您可能想确保您有一个 useffect ,以确保仅在您想要的条件下执行它。这将适用于一些有限数量的获取 - 对于动态的东西或大量的提取物,这种方法可能不太理想,并且您想要的东西可以更好。

If I'm understanding your question correctly, then I think you want something like this:

const [resp1, setResp1] = useState();
const [resp2, setResp2] = useState();

useEffect(() => {
    Promise.all([
        fetch('/api/...'),
        fetch('/api/...')
    ]).then(links => {
        const response1 = links[0];
        const response2 = links[1];
        
        setResp1(response1);
        setResp2(response2);
    })
}, [/*dependency array*/])

Here we leverage a useEffect to make your simultaneous fetches; we don't really need nor want to use await because we want them to run simultaneously and the Promise.all will only resolve when all the promises in the array resolve. In the .then of the Promse.all, you can parse out the responses just as you did in your original example and set them in state hooks you've defined earlier in your component. You'd probably want to make sure that you have an appropriately-defined dependency array passed as a second arg to your useEffect, in order to make sure that it only executes under the conditions in which you want it to. This would work for some limited number of fetches-- for something dynamic or with very large numbers of fetches, this approach would probably be less ideal, and you'd want something that scaled better.

倦话 2025-02-14 03:15:34

可以通过

  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]);
  });
};

和组件中创建一些辅助功能...

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 <>{/* ... */}</>;
};

This can be done nicely by

  1. Creating an array of URLs to resolve
  2. Iterating the returned array data
  3. Passing that data into your setters

For example, create some helper functions in some module

// 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]);
  });
};

and in your component...

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 <>{/* ... */}</>;
};
狼性发作 2025-02-14 03:15:34

尝试此尝试,

截至今天,现在在所有最新版本的主要浏览器中实现了Fetch,除了 IE11 外,包装器仍然可以有用,除非您对其使用多填充。

然后,利用新的且现在更稳定的JavaScript功能,例如破坏 and async/等待,您可能能够对同一问题使用类似的解决方案(请参阅代码以下)。

我相信,即使一见钟情似乎似乎有些代码,但实际上是一种更清洁的方法。希望它有帮助。

try {
  let [items, contactlist, itemgroup] = await Promise.all([
    fetch("http://localhost:3000/items/get"),
    fetch("http://localhost:3000/contactlist/get"),
    fetch("http://localhost:3000/itemgroup/get")
  ]);

  ReactDOM.render(
    <Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
      document.getElementById('overview');
  );
}
catch(err) {
  console.log(err);
};

Try this,

As of today, fetch is now implemented in all the latest version of the major browsers, with the exception of IE11, a wrapper could still be useful unless you use a polyfill for it.

Then, taking advantage of newer and now more stable javascript features like destructuring and async/await, you might be able to use a similar solution to the same problem (see the code below).

I believe that even though at first sight may seem a little more code, is actually a cleaner approach. Hope it helps.

try {
  let [items, contactlist, itemgroup] = await Promise.all([
    fetch("http://localhost:3000/items/get"),
    fetch("http://localhost:3000/contactlist/get"),
    fetch("http://localhost:3000/itemgroup/get")
  ]);

  ReactDOM.render(
    <Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
      document.getElementById('overview');
  );
}
catch(err) {
  console.log(err);
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文