【问题标题】:Can't access to my data from a SWR fetch - React无法从 SWR 获取访问我的数据 - React
【发布时间】:2020-02-24 11:45:11
【问题描述】:

您好,我尝试构建一个从 API 获取数据的应用程序。 我使用 SWR Hooks 来获取数据

// libs/fetch.js
import fetch from "isomorphic-unfetch"

export default async function(...args) {
  const res = await fetch(...args)
  return res.json()
}
// App.js
import React, { useEffect } from "react"
import "./styles.css"
import useSWR from "swr"
import fetch from './libs/fetch'

export default function App() {
  const url = "https://data.grandpoitiers.fr/api/records/1.0/search/?dataset=mobilites-stationnement-des-parkings-en-temps-reel&facet=Places_restantes"
  const { data, error } = useSWR(url, fetch)
  return (
    <div className="App">
      {JSON.stringify(data)}
    </div>
  )
}

我无法访问数据值。当我尝试data.records 它返回Cannot read property 'records' of undefined

我不知道该怎么办,我搜索但我没有找到答案。

编辑: https://codesandbox.io/s/github/MattixNow/PoitiersParker/tree/80871ba94769346a7008312bdb6e4c1143e591a3

有人可以帮助我吗?感谢您的回复

【问题讨论】:

    标签: reactjs fetch


    【解决方案1】:

    根据文档,您必须处理错误和加载情况

    export default function App() {
        const url =
            "https://data.grandpoitiers.fr/api/records/1.0/search/?dataset=mobilites-stationnement-des-parkings-en-temps-reel&facet=Places_restantes"
        const { data, error } = useSWR(url, fetch)
    
        if (error) return <div>failed to load</div>
        if (!data) return <div>loading...</div>
    
        return (
            <div className="App">
    
                {JSON.stringify(data.records)}
            </div>
        )
    }
    

    【讨论】:

    • !数据检查真的很重要。在我的情况下,api fetch 需要一些时间,所以它导致了未定义的错误并且页面加载被停止。但是使用这个反应渲染加载......直到数据获取完成。
    • 这里也一样。检查 !data 让它在这里工作。好像也花了点时间。感谢您的回答和评论
    • 这个答案并没有解决我的确切问题。
    【解决方案2】:

    在我的例子中,我刚刚在调用 useSWR 之前添加了default SWR fetcher 函数:

      const fetcher = async (url) => {
        const res = await fetch(url);
    
        // If the status code is not in the range 200-299,
        // we still try to parse and throw it.
        if (!res.ok) {
          const error = new Error("An error occurred while fetching the data.");
          // Attach extra info to the error object.
          error.info = await res.json();
          error.status = res.status;
          throw error;
        }
    
        return res.json();
      };
    

    我没有使用它:

    const { data, error } = useSWR(url, fetch)
    

    看哪,loading... 的出发日期和日期在这里 :)

    【讨论】:

      【解决方案3】:

      在我的例子中,有时数据是一个字符串,有时数据是一个对象,我不得不将我的 fetcher 更改为 async/await。

      奇怪的是,当数据是字符串时,它只是缺少结束的'}'

      export const fetcher = async <T = any>(url: string) => {
        const { data } = await api.get<T>(url);
        return data;
      };
      

      【讨论】:

        【解决方案4】:

        在从服务器获取数据之前,首先或同时运行 JSON.stringify(data.records)。发生错误,因为它是在从服务器获取数据之前执行的。

          <div className="App">
        
              {
                data&&
        
                JSON.stringify(data.records)
              }
        
          </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-31
          • 1970-01-01
          • 1970-01-01
          • 2019-08-12
          • 1970-01-01
          • 1970-01-01
          • 2018-11-07
          • 1970-01-01
          相关资源
          最近更新 更多