[英]Question About Which Order React Components Run In Relation To Async Functions
我有一個應用程序,在用戶加載它時,它使用 Javascript 的內置 API 來獲取地理位置數據。 然后,它將這些數據傳遞給一個組件,該組件應該在對 OpenWeather 的 API 調用中使用它。 但是,API 調用發生在 Geolocation 加載之前。 我試過讓我的 useLocation function 異步等待(成功),但它沒有用。
這是我的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 在異步的 function 回調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
回調 function 中。
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")
}
這是結果代碼,但我將默認位置 state 更改為 null,因為經度和緯度值設置為零是有效坐標。
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 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>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.