[英]How to iterate over nested JSON with Map in JSX
不知道如何访问 json object 的内部。 我尝试使用 Map 遍历location
部分并获取capital
,但我收到错误Cannot read property 'map' of undefined
如果我 console.log 只是item.location
我得到:
Objects are not valid as a React child (found: object with keys..
If you meant to render a collection of children, use an array instead.
所以不确定我需要做什么才能呈现item.location.capital
json 数据:
{
"ip": "100.200.00.000",
"type": "ipv4",
"continent_code": "NA",
"continent_name": "North America",
"country_code": "US",
"country_name": "United States",
"region_code": "LA",
"region_name": "bogus",
"city": "place",
"zip": "90210",
"latitude": 316,
"longitude": 123,
"location": {
"geoname_id": 1234,
"capital": "Washington D.C.",
"languages": [
{
"code": "en",
"name": "English",
"native": "English"
}
],
"country_flag": "http://assets.ipstack.com/flags/us.svg",
"country_flag_emoji": "🇺🇸",
"country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
"calling_code": "1",
"is_eu": false
}
}
反应
useEffect(() => {
fetch("http://api.ipstack.com/check?access_key=" + accessKey)
.then((response) => response.json())
.then((data) => {
setIpData(data)
})
}, [])
return (
<div className="ip-results">
<h5>IP ADDRESS</h5>
{ipData.ip}
<h5>LOCATION</h5>
{ipData.region_name}
<h5>City</h5>
{ipData.city}
<h5>zip</h5>
{ipData.zip}
<h5>zip</h5>
{ipData.location.capital}
</div>
)
可能是您有一些没有位置键的项目?
你可以试试这个并确认你是否得到同样的错误:
{item.location ? <> {item.location.map((l, i) => (
<p key={i}>{l.capital}</p>
))} </> : null}
location
是 Object,而不是数组。
"location": {
"geoname_id": 1234,
"capital": "Washington D.C.",
"languages": [
{
"code": "en",
"name": "English",
"native": "English"
}
],
"country_flag": "http://assets.ipstack.com/flags/us.svg",
"country_flag_emoji": "🇺🇸",
"country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
"calling_code": "1",
"is_eu": false
}
看起来capital
有一个字符串值,所以你可以把
<p>{item.location.capital}</p>
你可以这样做: <p>{item.location.capital}</p>
但有些项目没有location key
,即在某些项目上你会得到undefined
。
你不能通过location
map 因为它是一个 object 不是数组,你可以通过location
map 这个:
`Object.keys(item.location).map((item, i)=> {
// your code here
// e.g : console.log(item["capital"])
// output : "Washington D.C."
}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.