簡體   English   中英

React Geocode 包在 React 中返回已實現的 Promise 對象

[英]React Geocode package returns fulfilled Promise object in React

我有一個狀態,用於在頁面加載時接收用戶位置。

  const [userLocation, setUserLocation] = useState({
    lat: null,
    lng: null,
    userAddress: ''
  })

我創建了一個 getAddress 函數,該函數旨在使用 react Geocode npm 包基於坐標返回地址的字符串值

  const getAddress = async (lat, lng) => {
    try {
      const res = await Geocode.fromLatLng(lat, lng)
      const address = res.results[0].formatted_address;
      return address

    } catch (err) {
      console.log(err.message)
    }

  }

我的 getUserLocation 函數在頁面加載時在 useEffect 中運行

  const getUserLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  }

  const showPosition = (position) => {
    setUserLocation({
      ...userLocation,
      lat: position.coords.latitude,
      lng: position.coords.longitude,
      userAddress: getAddress(position.coords.latitude, position.coords.longitude)
    })
  }

我的 userLocation 對象返回如下:

USER LOCATION 
{lat: 43.829601, lng: -79.470408, userAddress: Promise}
lat: 43.829601
lng: -79.470408
userAddress: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "126 Seabreeze Ave, Thornhill, ON L4J 9H1, Canada"
[[Prototype]]: Object

我希望返回承諾結果值,而不是其他任何明顯的東西。 有什么解決辦法嗎?

因為異步函數返回一個承諾,調用一個會給你承諾,而不是結果。

在這里,您直接調用getAddress

userAddress: getAddress(position.coords.latitude, position.coords.longitude)

但是,如果您想要結果,則必須使showPosition異步,並await getAddress的結果:

const showPosition = async (position) => {
    setUserLocation({
      ...
      ...
      ...
      userAddress: await getAddress(position.coords.latitude, position.coords.longitude)
    })
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM