繁体   English   中英

Redux-Saga行为模式

[英]Redux-Saga behavior pattern

这样的传奇效果非常好:

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内部,因为其他工作的reducer是:

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

而且我没有actionCreater。 据我了解, put方法既可以调度动作,也可以设置actionCreator。 如何将坐标放入状态树?

您的问题是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满足时才会产生,并将实现的值返回给您的saga以供进一步使用。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM