gpt4 book ai didi

javascript - react /归零 : get the user geolocation using a promise and dispatch the position to the action creator

转载 作者:行者123 更新时间:2023-11-30 14:42:29 25 4
gpt4 key购买 nike

在我的 store.js 中,我试图从浏览器获取最终用户的地理位置,然后发送一个 Action 创建器,但这并没有发生。

function showPosition(position) {
console.log("showPosition");
//console.log(position);
return position;
}

function getLocation() {
// Get the current 'global' time from an API using Promise
console.log("getLocation")
return new Promise((resolve, reject) => {
if (navigator.geolocation) {
console.log("Boolean navigator.getLocation:" + Boolean(navigator.geolocation))
Promise.resolve(navigator.geolocation.getCurrentPosition(showPosition))
} else {
Promise.reject("Geolocation is not supported by this browser.")
}
})
}

function loadNearbyShops() {
return function (dispatch) {
return getLocation().then(
position => dispatch(getCoords(position))
).catch(
error => console.log(error)
);
};
}

store.dispatch(loadNearbyShops())

但这不会触发我下面的 Action 创建器

另一方面,我的 action creator 定义为:

export function getCoords(position) {
console.log(position)
return {
type: 'GET_LOCATION',
long: position.coords.longitude,
lat: position.coords.latitude
}
}

最佳答案

getLocation 函数固定为:

function getLocation() {
return new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(pos => {
showPosition(pos);
resolve(pos);
});
} else {
reject("Geolocation is not supported by this browser.")
}
)};
}

关于javascript - react /归零 : get the user geolocation using a promise and dispatch the position to the action creator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com