【发布时间】:2022-01-14 12:21:20
【问题描述】:
TypeError: Cannot read properties of undefined (reading 'city')
我正在尝试遍历地址键和值,但失败了,然后我尝试一次访问一个值,我得到了那个错误。我是 React 和 JS 的新手。当我尝试记录该值时,我得到了没有问题的答案,但是一旦我想在屏幕上打印出来,就会弹出错误。我已经尝试了我能想到并在网上找到的可能方法,但遗憾的是没有任何效果。
//this is a component that is supposed to show details of each hero
const HeroPage = () => {
const { id } = useParams();
const [hero, setHero] = useState({});
useEffect(() => {
const fetchHero = async () => {
const res = await fetch(
`https://jsonplaceholder.typicode.com/users/${id}`);
const data = await res.json();
setHero(data);
};
fetchHero();
}, [id]);
const address = hero.address;
return (
<div className="card-container-page box">
<div className="box-middle">
<h1>{hero.name}</h1>
<h3>{hero.email}</h3>
<h3>{hero.phone}</h3>
<h3>{address.city}</h3>
// I have also tried the following code
{Object.keys(hero).map((keyName, i) => (
<li className="card-container" key={i}>
<span className="input-label">
key: {i} Name: {hero[keyName]}
</span>
</li>
))}
</div>
</div>
);
};
export default HeroPage;
//JSON response I get
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}]
//https://jsonplaceholder.typicode.com/users
【问题讨论】:
-
请出示相关代码。这里没有循环。
-
无关,但你的useEffect除了
id之外,还应该依赖hero和setHero -
const { id } = useParams(); const [英雄,setHero] = useState({});我使用 map() 循环遍历它并没有工作。
-
请编辑问题以显示您尝试过的内容。
-
@Codebling 我刚刚编辑了代码以包含我之前尝试过的内容。我不明白为什么。
标签: javascript reactjs json