所以我有一个fetch请求,它返回这个json:
{
"data":[
{
"latitude":44.43225,
"longitude":26.10626,
"type":"locality",
"name":"Bucharest",
"number":null,
"postal_code":null,
"street":null,
"confidence":1,
"region":"Bucharest",
"region_code":"BI",
"county":null,
"locality":"Bucharest",
"administrative_area":null,
"neighbourhood":null,
"country":"Romania",
"country_code":"ROU",
"continent":"Europe",
"label":"Bucharest, Romania"
}
]
}在组件中,我想要显示纬度和经度,我尝试了这种方式:
const conditions = (props) => {
return (
<div className={classes.Wrapper}>
{
props.error && <small className={classes.Small} > Please enter a valid city. </small>}
{
props.loading && < div className={classes.Loader} />}
{
props.responseObj.cod === 200 ?
<div className={classes.information}>
<p>{props.geoObj.data[0].longitude}</p>
<p>{props.geoObj.data[0].latitude}</p>
</div > : null
} </div>
)
}但它不起作用。您能告诉我哪里出了问题吗?我应该如何使用JSON响应中的对象?
发布于 2021-07-31 02:45:30
我想你得先把JSON文件转换成Obj。尝试使用JSON.parse()
这篇文章可能会有所帮助:How to read an external JSON
发布于 2021-07-31 02:47:36
你正确地使用了它。但是当你获取数据时,props geoObj没有像fetch响应那样的结构。
您需要使用[optional chaining][1]来避免相关问题:
{props.geoObj?.data?.[0]?.longitude}发布于 2021-07-31 03:17:45
是像这样吗?
const props = {
"data":[
{
"latitude":44.43225,
"longitude":26.10626,
"type":"locality",
"name":"Bucharest",
"number":null,
"postal_code":null,
"street":null,
"confidence":1,
"region":"Bucharest",
"region_code":"BI",
"county":null,
"locality":"Bucharest",
"administrative_area":null,
"neighbourhood":null,
"country":"Romania",
"country_code":"ROU",
"continent":"Europe",
"label":"Bucharest, Romania"
}
]
}
type Data = typeof props.data[0]
const Condition = (props: Data) => <div>{
JSON.stringify(props)}</div>
const Parent = () => {
return <div>
{
props.data.map(data => <Condition {...data} />)
}
</div>
}https://stackoverflow.com/questions/68598654
复制相似问题