redux-saga:如何以编程方式为收益创建多个调用/副作用?

IT技术 reactjs react-native ecmascript-6 redux redux-saga
2021-05-02 03:53:56

使用 redux-saga,可以并行执行多个效果:

import { call } from 'redux-saga/effects'

// correct, effects will get executed in parallel
const [users, repos]  = yield [
  call(fetch, '/users'),
  call(fetch, '/repos')
]

我如何以编程方式创建这些“呼叫”呼叫

我想要实现的是:

假设我有一个具有不同参数的数组,我想对每个参数执行对服务器的请求,但与 redux-saga 并行:

const parameters = ['abc', 'def', 'ghi']

const allMyFetchCalls  = parameters.map( (p) => makeCallRequestWithParameter(p) );

makeCallRequestWithParameter 将创建一个函数调用(或在 redux-saga-speech 中:一个效果)call(fetch, param)就像在yield call(fetch, param)

const resultArray = yield allMyFetchCalls;

这是可能的,如果是,如何?

3个回答

请注意,当时call效果并没有调用任何东西。它只是创建纯 JavaScript 对象并返回。所以你想要的并没有那么难。

import { call } from 'redux-saga/effects'

const params = ['abc', 'def', 'ghi']
const responses  = yield params.map(p => call(fetch, p))

因此,根据截至 2019 年 11 月 17 日redux saga 文档,为了使其并行执行,您需要使用 all()

yield all( arrayOfSomething.map( eachSomething => call( myFunction, eachSomething ) ) )

或者如果你想在打电话之前计算一些东西

yield all( arrayOfSomething.map( eachSomething => {
   // do some computations

   // important you return the function which is automatically done 
   // for you in the one line map, this has gotten me a few 
   // times when I am just coding fast
   return call( myFunction, eachSomething ) )
} )

这可能也有效https://github.com/redux-saga/redux-saga/tree/master/docs/api#alleffects

function* mySaga() {
  const { customers, products } = yield all({
    customers: call(fetchCustomers),
    products: call(fetchProducts)
  })
}