【发布时间】:2020-12-27 08:03:58
【问题描述】:
不确定如何访问 json 对象的内部。我尝试使用 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>
)
【问题讨论】:
标签: javascript json reactjs jsx