【问题标题】:redux-saga: race between action and event channelredux-saga:动作和事件通道之间的竞赛
【发布时间】:2018-08-11 14:27:22
【问题描述】:

我想使用 redux-saga 在 redux 操作和事件通道之间进行竞赛。

export function * createEventChannel () {
    return eventChannel(emit => {
       MyModule.addEventListener(MyModule.MY_EVENT, emit)
       return () => { MyModule.removeEventListner(MyModule.MY_EVENT, emit)}
    })
}

....

function * raceWithActionAndEvent() {
   const channel = yield call(createEventChannel)

   // I want to race between Redux Action: 'MY_ACTION' and channel here 
}

【问题讨论】:

    标签: ecmascript-6 redux redux-saga


    【解决方案1】:

    应该这样做:

    export function* raceWithActionAndEvent() {
        const channel = yield call(createEventChannel);
        const winner = yield race({
            channel: take(channel),
            action: take(MY_ACTION),
        });
    
        if (winner.action) {
             // then the action was dispatched first
        }
        if (winner.channel) {
            // then the channel emitted first
        }
    }
    

    在我看来,代码可读性很强。您在两个 takes 之间设置了一个 race,然后根据获胜者采取行动。

    请注意,createEventChannel 不需要是生成器函数(就像您在原始问题中所说的那样)

    【讨论】:

      猜你喜欢
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2020-04-18
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多