【问题标题】:Redux Saga navigator.geolocation.getCurrentPositionRedux Saga navigator.geolocation.getCurrentPosition
【发布时间】:2023-11-07 19:04:01
【问题描述】:

我使用 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) }

【问题讨论】:

    标签: javascript reactjs geolocation redux-saga


    【解决方案1】:

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

    location  => position.on({location}),
    error     => position.on({error}),
    

    对我有用的是创建一个在检索位置时解析的承诺定义。例如:

    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;
    }
    

    享受

    【讨论】: