簡體   English   中英

“TypeError:listOfTours.map 不是函數”當嘗試 map over Array

[英]"TypeError: listOfTours.map is not a function" when try to map over Array

我正在嘗試將我的 listOfTours 顯示為個人 div 的反應,但我收到以下錯誤:

TypeError: listOfTours.map is not a function

在前 1 或 2 秒內,它正確顯示所有內容,但隨后出現錯誤

我的數組:

const [listOfTours, setListOfTours] = useState([
    {
      tour_date: "2020-04-24",
      tour_distance: 15,
      tour_duration: 60,
      tour_elevation_down: 245,
      tour_elevation_up: 245,
      tour_name: "Fahrradtour 24.04.2020 19:07",
      tour_sport: "mtb",
    },
    {
      tour_date: "2020-04-23",
      tour_distance: 34,
      tour_duration: 143,
      tour_elevation_down: 426,
      tour_elevation_up: 426,
      tour_name: "Fahrradtour 23.04.2020",
      tour_sport: "mtb",
    }
  ]);

我的代碼為 Map 在陣列上:

return (
    <div>
      <div className="tourDisplay">
        {listOfTours.map((tour) => {
          return (
            <div>
              <div>Tourname: {tour.tour_name}</div>
              <div>...other values</div>
            </div>
          );
        })}
      </div>
    </div>
  );

這似乎與我如何讓我的數據做出反應有關

useEffect(() => {
    axios
      .get("/api/all-tours", {
        headers: {
          "x-access-token": localStorage.getItem("token"),
        },
      })
      .then((response) => {
        if (response.data.status === "error") {
          console.log(response.data.status);
        } else {
          setListOfTours(response.data);
        }
      });
  });

Since you're returning your data that you put into the State from an asyncrhonous call, it happens that when you invoke the function, your state is empty and the map doesn't find any data. 您可以通過不同的方式輕松解決此問題; 其中之一可以使用loading state

const [loading, setLoading] = useState(true);

然后你可以像這樣修改你的useEffect

useEffect(() => {
    axios
      .get("/api/all-tours", {
        headers: {
          "x-access-token": localStorage.getItem("token"),
        },
      })
      .then((response) => {
        if (response.data.status === "error") {
          console.log(response.data.status);
        } else {
          setListOfTours(response.data);
        }
      }).then(_ => {
         setLoading(false);
      });
  });

return時,您應該添加以下內容:

if(loading) return <p>Loading...</p>
else return (
  <div>
    <div className="tourDisplay">
      {listOfTours.map((tour) => {
        return (
          <div>
            <div>Tourname: {tour.tour_name}</div>
            <div>...other values</div>
          </div>
        );
      })}
    </div>
  </div>
);

最終,您可以將loading移動到 map function 附近,因此:

{loading ? <p>Loading...</p>
  : (listOfTours.map((tour) => {
        return (
          <div>
            <div>Tourname: {tour.tour_name}</div>
            <div>...other values</div>
          </div>
        );
}))}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM