繁体   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