【问题标题】:Pass arguments to saga dispatch - and get the argument to the handler将参数传递给 saga dispatch - 并将参数传递给处理程序
【发布时间】:2017-07-31 02:40:07
【问题描述】:

这是我现在的传奇:

function* upAsyncSaga() {
    yield takeEvery(UP_ASYNC, upAsyncHandler);
}

这里是相关的同步资料:

const UP_ASYNC = 'UP_ASYNC';
export function upAsync() {
    return {
        type: UP_ASYNC
    }
}
function* upAsyncHandler() {
    yield call(wait, 1000);
    yield put(up());
}

const UP = 'UP';
export function up() {
    return {
        type: UP
    }
}

我通过这样做store.dispatch(upAsync()) 触发upAsyncSaga。但是我想传递一个名为times 的参数。所以我想做store.dispatch(upAsync(3)) 然后我希望/想要像这个伪代码一样将参数传递给处理程序:

export function upAsync(times) { // this is the argument "times"
    return {
        type: UP_ASYNC
        times // here it is again
    }
}
function* upAsyncHandler(times) { // i want the argument to get to the handler
    for (let i=0; i<times; i++) {
        yield call(wait, 1000);
        yield put(up());
    }
}

这可能吗?

【问题讨论】:

    标签: redux-saga


    【解决方案1】:

    当我们派发任何动作到存储时,我们可以像这样包含参数(有效负载):

    store.dispatch( { type: UP_ASYNC, payload : { times: 2 }})
    

    修改你的函数:

    export function upAsync(type, payload) {
      const { type, times } = payload
        return {
            type: type,
            times: times
        }
    }
    

    我不确定您的完整存储实现如何,但如果您正在关注 redux-saga,上述内容应该可以解决您的问题。

    编辑:

    如果您有具有效果的 redux 商店(我相信),那么您可以简单地执行如下操作:

    dispatch({type: '<namespace>/upAsyncHandler', payload: {type: UP_ASYNC, times: 2}})
    

    这里,“命名空间”是指你在 redux 存储中的命名空间,你的处理程序被定义为一个效果。见下文:

    *upAsynHandler(action, { call }) {
      const { type, times } = action
      const res = yield call(wait, times)
    }
    

    【讨论】:

    • 感谢 Umesh,但我怎样才能将 payload 转换为 upAsyncHandler
    • 非常感谢,我现在终于明白了。请原谅我延迟接受您的解决方案。
    • 不工作。 actionundefined。仅当您不使用 root saga 时,您的解决方案才有效。设置 root saga 是错误的
    • @Green,这是经过验证和使用的解决方案,请在投反对票之前考虑一下
    【解决方案2】:

    当调用 dispatch 时,action 会被传递给 handler。

    function* myFn(action){
      const {type, counter} = action
      console.log(counter) // 0
    }
    
    function* mySaga() {
      yield effects.takeEvery('SET_STATE', myFn)
    }
    
    run(mySaga)
    
    store.dispatch({type: 'SET_STATE', counter: 0})
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多