[英]"TypeError: listOfTours.map is not a function" when try to map over Array
I'm trying to display my listOfTours as individuals divs's in react, but I'm getting the following error:我正在尝试将我的 listOfTours 显示为个人 div 的反应,但我收到以下错误:
TypeError: listOfTours.map is not a function
for the first 1 or 2 seconds it displays everything correctly but then the error comes up在前 1 或 2 秒内,它正确显示所有内容,但随后出现错误
My Array:我的数组:
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",
}
]);
My Code to Map over the Array:我的代码为 Map 在阵列上:
return (
<div>
<div className="tourDisplay">
{listOfTours.map((tour) => {
return (
<div>
<div>Tourname: {tour.tour_name}</div>
<div>...other values</div>
</div>
);
})}
</div>
</div>
);
It seems to have something todo with how i get my data to react这似乎与我如何让我的数据做出反应有关
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. 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. You can solve easily this problem in different way;您可以通过不同的方式轻松解决此问题; one of them could be use a
loading state
.其中之一可以使用
loading state
。
const [loading, setLoading] = useState(true);
Then you can modify your useEffect
like that:然后你可以像这样修改你的
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);
});
});
And on the return
you should add this:在
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>
);
Eventually, you can move the loading
near the map function, so:最终,您可以将
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.