Redux-Saga行为模式

问题描述 投票:0回答:1

这样的传奇非常有效:

function* getPosition() {
  yield navigator.geolocation.getCurrentPosition(function(pos) {
    console.log(`I am getPosition: ${pos.coords.latitude}, ${pos.coords.longitude}`);
  });
}

但我需要Redux状态树中的坐标。所以,我尝试了一些模式,但没有一个模式可行。 1)无法从getCurrentPosition范围中获取变量

function* getPosition() {
  let position = {};
  yield navigator.geolocation.getCurrentPosition(function(pos) {
    position = pos;
  });
  // either
  console.log(`I am getPosition: ${position.coords.latitude}, ${position.coords.longitude}`);
  // or
  yield console.log(`I am getPosition: ${position.coords.latitude}, ${position.coords.longitude}`);
  // Any of two is undefined
}

2)无法返回并赋值:

function* getPosition() {
  const position = yield navigator.geolocation.getCurrentPosition(function(pos) {
    return pos;
  });
  yield console.log(`I am getPosition: ${position.coords.latitude}, ${position.coords.longitude}`);
}

3)方法放置无效:

function* getPosition() {
  yield navigator.geolocation.getCurrentPosition(function(pos) {
    // Pos fetched
    console.log(`I am getPosition: ${pos.coords.latitude}, ${pos.coords.longitude}`);
    // Nothing happens. State is empty object.
    put({
      type: LOCATION_SET_POSITION,
      pos
    });
  });
}

locationReducer在rootReducer中,因为其他工作的reducers是:

locationReducer.js
export function locationReducer(state = {}, action) {
  switch (action.type) {
    case LOCATION_SET_POSITION:
      return action.pos
    default:
      return state;
  }
}

我没有actionCreater。据我了解,put方法都调度一个动作并设置actionCreator。如何将坐标放到状态树?

javascript redux-saga
1个回答
3
投票

你的问题是geolocation.getCurrentPosition是异步的,但是处于成功/错误回调样式,而你需要它作为一个承诺被送到redux-saga

function* getPositionSaga() {
    const getCurrentPosition = () => new Promise(
      (resolve, reject) => navigator.geolocation.getCurrentPosition(resolve, reject)
    )
    const pos = yield call(getCurrentPosition)
    yield put({type: LOCATION_SET_POSITION, pos})
}

在这里,我们将getCurrentPosition包装成一个返回Promise<Position>的函数

call是一个redux-saga效应,如果它给出的函数返回一个promise,它只会在满足该promise时产生,并且会将已实现的值返回到你的传奇中以供进一步使用。

put是一种效果,最终将通过redux调度给定的动作对象

任何redux-saga效果都必须从生成器中产生,而不是直接调用,因为它们只返回一个简单的redux-saga中间件执行器指令对象(而不是立即实际执行副作用)。执行程序只能在从生成器中获取时访问和控制它们,因此在回调中使用它们(如示例3)将无法像您期望的那样工作

© www.soinside.com 2019 - 2024. All rights reserved.