redux 如何使用React-Thunk调用生成器函数

lstz6jyr  于 2023-06-30  发布在  React
关注(0)|答案(2)|浏览(125)

我正在把一些传奇故事改编成小说。其中一些传奇故事有嵌套的生成器函数,我不能在thunks中调用这些函数。通常在一个 Saga 我做:

const result = yield call(myFunction, anotherSaga, params);

但是,当我尝试将其转换为Thunk时,就像:

export const myAction = createAsyncThunk(
  'myAction',
  async (data: Payload, { dispatch, getState }) => {

     const result = myFunction(anotherSaga, params).next().value;

     console.log(result)
})

console:
    @@redux-saga/IO: true
    combinator: false
    payload: {context: null, args: Array(2), fn: ƒ}
    type: "CALL"

我没有得到任何可用的东西,因为anotherSaga嵌套了sagas。如何将其转换为形实转换函数?

gzjq41n4

gzjq41n41#

你不能直接从thunk调用 Saga ,saga使用的效果需要由saga库处理。
一些可能的解决方法:
a)甚至将嵌套的 Saga 转换为非生成器函数
B)如果结果并不重要,您可以将call替换为分派,然后在分派此类操作时使用takeEvery效果调用 Saga
c)我不推荐这样做,但是使用saga中间件示例运行 Saga 在技术上是可行的

export const myAction = createAsyncThunk(
  'myAction',
  async (data: Payload, { dispatch, getState }) => {
     const task = sagaMiddleware.run(anotherSaga, params)
     const result = await task.toPromise()
     console.log(result)
})
ojsjcaue

ojsjcaue2#

**免责声明:**我的回答可能有偏见,因为我是以下建议库的作者。

可以使用redux-thaga。你可以创建一个thaga(是的,它就是thaga)而不是一个thunk,然后在它的回调中你可以fork或者简单地调用另一个 Saga 。

export const myAction = createThagaAction('myAction', function* (data: Payload) {
  const result = yield call(anotherSaga, params);
  console.log(result)
});

function* rootSaga() {
  // make sure to register you thaga worker
  yield takeLatest(myAction, myAction.worker);
}

// somewhere in the code
await dispatch(myAction(data)); // yes, it is await-able

相关问题