我正在尝试用REACT建立一个网站。在主页上有两个按钮,欧洲和美国。假设您单击了“欧洲”。然后你会看到欧洲所有国家的列表。当你点击一个国家时,你应该会看到这个国家的城市列表。
问题是,我如何访问“城市”中的项目?
const DATA = [
{
id: 1,
title: "EUROPE",
countries: [
{
id: 1,
country: "france",
cities: [
{
id: 1,
city: "paris"
},
{
id: 2,
city: "toulouse"
}
];
// so at homepage, you click "europe", and on the second page i got this:
const StateCard = () => {
const { title } = useParams();
const selectedData = DATA.find( d => d.title === title);
return(
<div className="main">
{selectedData &&
selectedData.countries.map((item, id) => {
return (
<div className="card-container" >
<Link key={id} to={`${title}/${item.country}`}> {item.country} </Link>
</div>
);
})}
</div>useParams给我们返回了第一次点击后添加到网址的标题,即“欧洲”。selectedData返回了“EUROPE”中的项:{id: 1,title:"EUROPE",countries: Array(1)}
现在屏幕上显示“法国”。你点击了法国,现在我想显示里面的两个城市。我得到的只有:
const { country } = useParams();这给了我们“法兰西”。但是我不知道如何进入里面的城市。我试着使用DATA.countries.find(),但是我放在DATA之后的任何东西。给我"TypeError:无法读取未定义的属性'find‘“。
对不起,太长了,谢谢你们!
发布于 2021-06-22 06:30:29
你可以先找到Country,然后在countriesResult上找到citiesResult,然后再从citiesResult.cities找到城市。
您将收到错误**TypeError: Cannot read property 'find' of undefined**,因为
您正在做的是DATA.countries.find()。Data是一个数组,所以你不能对它使用.countries。您必须使用find或索引来查找国家/地区。
const DATA = [{
id: 1,
title: "EUROPE",
countries: [{
id: 1,
country: "france",
cities: [{
id: 1,
city: "paris",
},
{
id: 2,
city: "toulouse",
},
],
}, ],
}, ];
const title = "EUROPE";
const country = "france";
const countriesResult = DATA.find((d) => d.title === title);
const citiesResult = countriesResult.countries.find(
(c) => c.country === country
);
const result = citiesResult.cities.map((c) => c.city);
console.log(result);
https://stackoverflow.com/questions/68075339
复制相似问题