【问题标题】:get information out of an API URL in JavaScript or react从 JavaScript 中的 API URL 获取信息或做出反应
【发布时间】:2021-06-23 23:40:32
【问题描述】:

我有主网址,每次访问都需要授权标头。

//console.log 包含此数据 - 帐户:[{categoryId:"some info"... }]

  • api/v2/accounts

我需要从第一个获取 accountId 和 categoryId 以获取更多信息,然后从第二个获取其他 url 的信息,依此类推 示例:

  1. /api/v2/accounts/accountId
  2. /api/v2/accounts/accountId/categoryId
  3. /api/v2/accounts/accountId/categoryId/feed/feedId 等

最好的方法是什么? 我无法一次获取所有内容,因为它们相互依赖,并且它们都没有我需要在我的应用程序中取得进展的所有信息。 此外,如果我第一次获取构建下一个 URL,我假设我需要再次获取新 URL 才能使用它。

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:

    我建议你看看react-query

    它可以帮助您使用 React 应用程序状态构建数据获取。这样,您将能够使用您的路由器参数从 URL 轻松检索并传递 id 并在状态更改时动态构建您自己的 URL。

    您可以在没有它的情况下解决此问题,只需使用fetchasync/awaitasync.js 等某种工具,具体取决于您的堆栈和要求。

    【讨论】:

      【解决方案2】:

      使用 async/await 您可以一个接一个地运行请求。

      const getFeed = async () => {
        const accountIdData = await fetch(
          '/api/v2/accounts/accountId', 
          { headers: { 'Authorization': ...}
        );
      
        // Use accountIdData in the below url
        const categoryIdData = await fetch(
          `/api/v2/accounts/${accountIdData.id}/categoryId`, 
          { headers: { 'Authorization': ...}
        );
      
        // Use categoryIdData in the below url
        const feedIdData = await fetch(
          `/api/v2/accounts/${accountIdData.id}/${categoryIdData.id}`, 
          { headers: { 'Authorization': ...}
        );
      
        // Do something with feed data
      }
      

      【讨论】:

        【解决方案3】:

        是的。您必须连续获取它们。

        const fetchData = async () => {
          const accountData = await axios.get("api/v2/accounts", accountToFetch)
          const accountId = await axios.get("/api/v2/accounts/accountId", accountData)
          const accountCategory = await axios.get("/api/v2/accounts/accountId/categoryId", accountData)
          ...
          // return data
        }
        

        【讨论】:

        • 为什么要带axiosfetch 无处不在,react-native.
        猜你喜欢
        • 2022-06-13
        • 2019-05-30
        • 2021-05-16
        • 2021-07-01
        • 2021-06-24
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 2021-11-30
        相关资源
        最近更新 更多