redux-saga 使用正则表达式

redux-saga take with regular expression

我正在为我的 Web 应用程序使用 redux-saga,但是我遇到了一个问题,我希望能够创建一个 saga 来处理多种不同的请求类型。为此,我希望能够将 taketakeEvery 与正则表达式一起使用。例如:

'foo/SOME_REQUEST'
'bar/SOME_REQUEST'
'baz/SOME_REQUEST'

都应该通过这样的方式处理:

yield takeEvery('*/SOME_REQUEST', handler);

有谁知道这是否可能或如何实现?

这是一个示例代码。

演示:http://kuy.github.io/redux-saga-examples/takex.html
GitHub: https://github.com/kuy/redux-saga-examples/tree/master/takex

您可以使用

yield takeLatest( action => /SOME_REQUEST$/.test(action.type), handler)

yield take( action => /SOME_REQUEST$/.test(action.type))

正如@lukehedger 在这里指出的那样:github issue

查看文档:take(pattern)

您需要使用自定义效果。

 //effect.js
    
 export const takeEveryRegex = (pattern, saga, ...args) =>
  fork(function* () {
    while (true) {
      const action = yield take("*")
      if (pattern.test(action.type)) {
        yield fork(saga, ...args.concat(action))
      }
    }
  })

然后在你的传奇中,按照正常模式使用它。

//saga.js    

function* formFailureSaga({ payload, action }) {
  yield console.log("form failure SAGA", payload, action)
}
    
export function* watchFormFailureSaga() {
  yield takeEveryRegex(/^FAILURE[/s/S]*((?=.*FORM))/, formFailureSaga)
}