这样的故事很好用:
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内部:
locationReducer.js
export function locationReducer(state = {}, action) {
switch (action.type) {
case LOCATION_SET_POSITION:
return action.pos
default:
return state;
}
}我也没有actionCreater。据我所知,put方法既分发一个操作,又设置actionCreator。如何将坐标放置到状态树中?
发布于 2017-12-11 14:29:17
您的问题是,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是一个剩余的传奇效应,如果它被赋予的函数返回一个承诺,它只会在该承诺实现时屈服,并将实现的价值返回到您的传奇中以供进一步使用。
put是一种最终通过redux分派给定动作对象的效果。
任何redux-saga效应都必须从生成器中产生,而不是直接调用,因为它们只返回redux-saga中间件执行器的一个简单指令对象(而不是立即执行副作用)。执行器只能在从生成器生成时访问和控制它们,因此在回调中使用它们(如示例3)将不会像您期望的那样工作。
https://stackoverflow.com/questions/47753318
复制相似问题