javascript - React Geocode 包在 React 中返回已完成的 Promise 对象
问题描述
我有一个状态,用于在页面加载时接收用户位置。
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)
})
}
推荐阅读
- javascript - AlpineJs 3.9 更新不会将变量更新为 x-if="ok" 之类的模板
- spring - Keycloak 社交登录休息 API 重定向您的次数过多
- swift - 适用于 MacOS 的 MusicKit 导入
- javascript - 我正在做我的第一个小型 JavaScript 项目,但我有点卡住了
- python - 张量流 2.6 中的量化感知训练问题。AttributeError:“列表”对象没有属性“dtype”
- javascript - 如何将 JSON 数据嵌入到 discord.js 中
- python - TypeError:mappingproxy 类型的对象不是 JSON 可序列化的
- python - Discord.py 冷却时间(秒)
- typescript - TS 从字符串数组创建新类型的键
- reactjs - 在底部标签导航中隐藏抽屉导航标题