javascript data.map 不是react all API中的函数

4urapxun  于 2023-02-18  发布在  Java
关注(0)|答案(3)|浏览(119)

我试图调用简单的apiCall在react js,但这是给错误如下:-

data.map is not a function

SandBox Url:-
验证码:

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [data, setData] = useState();

  const apiCall = () => {
    fetch("https://fakestoreapi.com/products/1")
      .then((res) => res.json())
      .then((json) => {
        setData(json);
        console.log(data);
      });
  };

  useEffect(() => {
    apiCall();
  }, []);

  return (
    <div className="App">
      {data
        ? data.map((val) => (
            <div>
              <h2>{val.id}</h2>
            </div>
          ))
        : ""}
    </div>
  );
}

谢谢你的努力!

dsf9zpds

dsf9zpds1#

因为从API返回的数据是Object,并且对象没有map方法,所以可以使用Object.entriesObject.valuesObject.keys来迭代对象。

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [data, setData] = useState();

  const apiCall = () => {
    fetch("https://fakestoreapi.com/products/1")
      .then((res) => res.json())
      .then((json) => {
        setData(json);
      });
  };
  console.log(data);
  useEffect(() => {
    apiCall();
  }, []);

  return <div className="App">{
    data ? Object.entries(data).map(([key, value]) => <div><span>{ key }:</span><span>{ JSON.stringify(value) }</span></div>) : null
  }</div>;
}

9lowa7mx

9lowa7mx2#

https://fakestoreapi.com/products/1获取的数据是对象,而不是数组。不能仅对对象应用map方法。请阅读有关Maphere的信息

gmxoilav

gmxoilav3#

我编辑你的代码:出现此错误是因为数据是object而不是数组

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [data, setData] = useState();

  const apiCall = () => {
    fetch("https://fakestoreapi.com/products/1")
      .then((res) => res.json())
      .then((json) => {
        setData(json); // json is object not array
        console.log(data);
      });
  };

  useEffect(() => {
    apiCall();
  }, []);

  console.log(data);

  if (data) {
    return (
      <div className="App">
        <div>
          <h2>{data.id}</h2>
        </div>
      </div>
    );
  } else {
    return <></>;
  }
}

相关问题