【发布时间】:2021-08-19 01:41:35
【问题描述】:
我还在自学 React,并且在我遇到问题时正在做一个项目。
我有以下代码。
const Weather = (props) => {
const [weather, setWeather] = useState([]);
const [lat, setLat] = useState([]);
const [long, setLong] = useState([]);
useEffect(() => {
const fetchData = async () => {
navigator.geolocation.getCurrentPosition(function (position) {
setLat(position.coords.latitude);
setLong(position.coords.longitude);
});
await fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&appid=SomeID&units=imperial&exclude=minutely`
)
.then((res) => res.json())
.then((result) => {
setWeather(result);
console.log(result);
});
};
fetchData();
}, [lat, long]);
return (
<React.Fragment>
<div className={styles.weather}>
<div className={styles.weather__current}>{weather.current.temp}</div>
<div className={styles.weather__hourly}>Hourly</div>
<div className={styles.weather__daily}>5 Day</div>
</div>
</React.Fragment>
);
};
export default Weather;
我的问题是我的请求在“填充”经纬度之前发出了两次,在第三次尝试时它就很好了。所以我收到了 2 个错误请求的响应,第三个是我想要的。
我的理解是,在异步函数中,等待将“暂停”,直到所有先前的变量都“满足”。我可能误解了。
我可以“硬编码”这些值,一切都很好。
任何帮助将不胜感激。
【问题讨论】:
-
await 关键字将在 fetch Promise 被解析时等待。如果
navigator.geolocation.getCurrentPosition是一个承诺,您可以在它之前使用await。但它看起来不像一个承诺,我认为你可以将你的 fetch 移动到 getCurrentPosition 的回调中,你可以在其中设置状态并发送你的 fetch 请求。我认为您不再需要经纬度状态
标签: reactjs async-await