从fetch方法中的数组获取位置数据时出错



我想从位置状态中提取lat/long坐标,但我收到一个错误,说无法读取undefined[0]的属性。

我调用了天气函数中的get location函数,是不是遗漏了什么?

import Card from "../Card/Card";
import { useState } from "react";
const WeatherCard = () => {
const [location, setLocation] = useState();
// function gets users location, and sets it to location state
const getLocation = () => {
// uses navigator to get location
navigator.geolocation.getCurrentPosition((location) => {
// sets lat/long position to state[array]
setLocation([location.coords.latitude, location.coords.longitude]);
});
};
// function to get weather data from api
const getWeather = () => {
// calls getLocation function
getLocation();
// fetches weather data from api
fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${location[0]}&lon=${location[1]}&exclude={part}&appid=${process.env.REACT_APP_API_KEY}`)
// takes data and parses it to json
.then(res => res.json())
// sets weather data to console
.then(data => console.log(data))
}
// renders the weather card
return (
<Card>
<div>{location}</div>
<button onClick={getWeather}>Click</button>
</Card>
);
};
export default WeatherCard;

地理定位API是异步的,因此将getLocation函数修复为async:

const getLocation = async () => {
// uses navigator to get location
await navigator.geolocation.getCurrentPosition((location) => {
// sets lat/long position to state[array]
setLocation([location.coords.latitude, location.coords.longitude]);
});
};

最新更新