我使用redux saga创建了应用,但是我在地理位置方面遇到了问题。
其实我找到了解决方案,但我不知道它是如何工作的。

function userPositionPromised() {
  const position = {}
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition (
      location  => position.on({location}),
      error     => position.on({error}),
      { enableHighAccuracy: true }
    )
  }
  return { getLocation: () => new Promise(location => position.on = location) }
}

function* getUserLocation() {
  yield put({type: GET_LOCATION_REQUESTED});
  const { getLocation } = yield call(userPositionPromised)
  const { error, location } = yield call(getLocation)
  if (error) {
    console.log('Failed to get user position!', error)
    const { message, code } = error;
    yield put({type: GET_LOCATION_FAILED, payload: { code, message }});
  } else {
    console.log('Received User Location', location)
    const { latitude: lat, longitude: lng } = location.coords;
    yield put({type: GET_LOCATION_SUCCESS, payload: { lat, lng } });
  }
}

我了解getUserLocation,但是当涉及到userPositionPromised时,我却听不到。特别是这部分:
      location  => position.on({location}),
      error     => position.on({error}),


 return { getLocation: () => new Promise(location => position.on = location) }

最佳答案

我尝试运行上面的代码,这里出现错误

location  => position.on({location}),
error     => position.on({error}),
对我有用的是创建一个promise定义,该定义在检索位置时进行解析。例如:
const getUserLocation = () => new Promise((resolve, reject) => {
 navigator.geolocation.getCurrentPosition(
  location => resolve(location),
  error => reject(error),
 )
})
那么您只需像其他任何服务一样,从生成器内部调用它即可。
function* myGenerator() {
 const location = yield call(getUserLocation)
 const {latitude, longitude} = location.coords;
}
请享用

07-26 06:43