【问题标题】:Swr API request return error data.map is not a function in reactjsSwr API请求返回错误data.map不是reactjs中的函数
【发布时间】:2022-08-20 07:41:09
【问题描述】:

我正在尝试使用 useSWR() 库从 API 消费,并且要返回的数据是一个对象数组,所以我决定首先尝试 axios 方法通过执行以下操作来发出请求

    const fetcher = (url) => axios.get(url).then((resp) => resp.json());

但是这个提取器没有工作,所以我尝试使用 fetch 方法,我注意到数据被检索但我尝试映射,它给了我一个错误,说 data.map 不是一个函数。

    const fetcher = (...args) => fetch(...args).then((resp) => resp.json());

    function Swr() {
    const { data, error } = useSWR(
        \"https://callcaree.herokuapp.com/api/member\",
        fetcher,
        { suspense: true }
       );

      //the data
      console.log(data);

      if (error) {
        return <h1> There was an error!</h1>;
      }

      return (
        <div>
          {data?.map((props) => {
            <div key={props._id}>
              <h3>{props.title}</h3>
           </div>;
          })}
        </div>
      );
    }

    标签: reactjs react-hooks axios patch swr


    【解决方案1】:

    这显示错误,因为您用于映射的数据不是数组它的对象您在数据中有数据,在该数据中有另一个数据您必须使用该数据来映射我已经写了code in sandbox,以便您可以更好地理解它

    import axios from "axios";
    import useSWR from "swr";
    
    export default function App() {
    const fetcher = (url) => axios.get(url).then((resp) => resp);
    
    const { data, error } = useSWR(
    "https://callcaree.herokuapp.com/api/member",
      fetcher,
      {
        suspense: true
      }
    );
    if (error) {
      return <h1> There was an error!</h1>;
    }
    
    return (
      <div>
        {data.data.data.map((props) => {
          return (
            <div key={props._id}>
              <h3>{props.name}</h3>
            </div>
          );
        })}
      </div>
    );
    }
    

    【讨论】:

    猜你喜欢
    • 2021-10-24
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多