如何解决关于 React 组件运行顺序与异步函数相关的问题
我有一个应用程序,当用户加载它时,它使用 Javascript 的内置 API 来获取地理位置数据。然后,它将这些数据传递给一个组件,该组件应该在对 OpenWeather 的 API 调用中使用它。但是,API 调用发生在 Geolocation 加载之前。我曾尝试使我的 useLocation 函数异步等待(成功),但没有奏效。
这是我的 App.js
的代码 const useLocation = () => {
const [location,setLocation] = useState({lat: 0,long: 0})
useEffect(()=>{
const success = (position) =>{
let lat = position.coords.latitude
let long = position.coords.longitude
console.log(lat,long)
setLocation({lat: lat,long: long})
}
navigator.geolocation.getCurrentPosition(success)
},[])
return location;
}
function App() {
// Gets just the
const location = useLocation()
function App() {
// Gets just the
const location = useLocation()
const routes = ['nasa','openweather','zomato']
return (
<div className="App">
<Route exact path="/openweather">
<Weather position={location} />
</Route>
</div>
}
这是Weather.js
的代码import { useState,useEffect } from "react"
const Weather = ({ position }) => {
const long = position.long
const lati = position.lat
const APIKey = '1234'
const [weather,setWeather] = useState()
const initData = async () => {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lati}&lon=${long}&appid=${APIKey}`)
const weatherData = await response.json()
setWeather(weatherData)
console.log(response)
}
useEffect(()=> {
initData()
},[])
解决方法
Geolocation getCurrentPosition 在异步函数回调 success
上获取结果
const success = (position) => {
const lat = position.coords.latitude
const long = position.coords.longitude
console.log(lat,long)
}
navigator.geolocation.getCurrentPosition(success)
console.log('I will log before geolocation gets position')
为了使其同步,我们需要将它们包装在一个 Promise 中,并将解析放在 success
回调函数中。
const geolocationGetCurrentPosition = () => {
return new Promise((resolve,reject) => {
const success = (position) => {
const lat = position.coords.latitude;
const long = position.coords.longitude;
resolve({ lat,long });
};
const error = (err) => {
reject(err);
};
navigator.geolocation.getCurrentPosition(success,error);
});
};
const run = async () => {
await geolocationGetCurrentPosition()
console.log("I'm synchronous,I will log after geolocation gets position")
}
这是结果代码,但我将默认位置状态更改为 null,因为设置为零的经度和纬度值是有效坐标。
const geolocationGetCurrentPosition = () => {
return new Promise((resolve,error);
});
};
const useLocation = () => {
const [location,setLocation] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const { lat,long } = await geolocationGetCurrentPosition();
setLocation({ lat,long });
} catch (err) {
// err
}
}
fetchData();
},[]);
return location;
};
function App() {
const location = useLocation();
const routes = ["nasa","openweather","zomato"];
return (
<div className="App">
{location && (
<Route exact path="/openweather">
<Weather position={location} />
</Route>
)}
</div>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。