不知道如何访问json对象的内部。我曾尝试使用Map迭代
location
部分并获得capital
,但我得到了错误Cannot read property 'map' of undefined
如果我只控制台日志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
}
}
React
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,而不是Array。
"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
进行映射,因为它是一个对象而不是数组,您可以通过以下方式通过location
对象进行映射:
`Object.keys(item.location).map((item, i)=> {
// your code here
// e.g : console.log(item["capital"])
// output : "Washington D.C."
}`