【发布时间】:2020-11-11 10:31:03
【问题描述】:
我正在尝试访问在我的状态下使用 React 中的 useEffect 挂钩设置的属性,但我不断收到此错误未捕获“TypeError:无法读取未定义的属性'0'”。 这是我的代码:-
import React, { useState, useEffect } from "react";
const Geocode = (props) => {
const [location, setLocation] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await fetch(
`https://eu1.locationiq.com/v1/search.php?key=MY_KEY=${props.address}&format=json&limit=1`
);
const data = await response.json();
setLocation((location) => ({ ...location, data }));
}
fetchData();
}, [props.address]);
const latitude = location.data[0].lat;
const longitude = location.data[0].lon;
return (
<div>
<h2>Location</h2>
{location && (
<p>
Lat: {latitude}, Lon: {longitude}
</p>
)}
</div>
);
};
export default Geocode;
以下 API 调用的输出是:-
[{…}]
0:
boundingbox: (4) ["-1.444471", "-1.163332", "36.6509378", "37.1038871"]
class: "place"
display_name: "Nairobi, Kenya"
icon: "https://locationiq.org/static/images/mapicons/poi_place_city.p.20.png"
importance: 0.73502675943376
lat: "-1.2832533"
licence: "https://locationiq.com/attribution"
lon: "36.8172449"
osm_id: "9185096"
osm_type: "relation"
place_id: "237011109"
type: "city"
__proto__: Object
length: 1
__proto__: Array(0)
【问题讨论】:
标签: javascript reactjs api use-effect