相当于 Redux thunks 中的收益 Take Redux Saga

Posted

技术标签:

【中文标题】相当于 Redux thunks 中的收益 Take Redux Saga【英文标题】:Equivalent of a yield take Redux Saga in Redux thunks 【发布时间】:2021-12-30 03:54:42 【问题描述】:

我目前正在将代码库中的 sagas 转换为 thunk。

我知道 Sagas 的特定功能,例如 yield putyield call 可以“直接翻译”为 thunk dispatch(...)await fn...

我遇到了yield take,据我了解,它采用存储中包含的一组操作并指示中间件等待来自存储的指定操作之一,结果是一个被调度的操作对象?

如果使用 Redux thunk,“等效”是什么?

非常感谢!

【问题讨论】:

如果没有自定义中间件,您将无法侦听 thunk 中的操作。 redux 和 redux-toolikt 的维护者正在为 RTK 开发一个 API,尽管 npmjs.com/package/@rtk-incubator/action-listener-middleware 应该做类似的事情 【参考方案1】:

传奇示例:

export function* sample() 
    try 
        const response = yield call(api.sample)
        yield put(setData(response.data))
     catch (error) 
        yield put(setError(error))
    


export function* sampleSaga() 
yield takeEvery( YOUR_TYPE, sample)

如果你想把它改成 redux thunk ,你可以这样做:

 export function sample()
   return (dispatch, getState) => 
     api.sample()
     .then((response)=> dispatch(setData(response.data)))
     .catch(error => Promise.reject(error))
  
 

【讨论】:

产量在哪里发挥作用? generator 函数的行为就像一个循环,当你使用 yield 时,它会停止,所以运行下一个 yield 方法,你使用 next 方法,你可以使用 takeEvery 方法运行所有的 yield 方法,在 thunk我们没有这样的东西,那么你不需要任何替代方法

以上是关于相当于 Redux thunks 中的收益 Take Redux Saga的主要内容,如果未能解决你的问题,请参考以下文章

安装了 redux-thunk 的 redux 操作中的异步函数错误

NextJS 和 Redux-thunk:出现“错误:“getInitialProps”中的循环结构”

使用 Redux Thunk 时正确理解 useEffect 中的依赖数组

使用 redux-thunk 从 React Native 中的动作创建者返回 Promise

在特定调度后从组件级别重定向 - redux thunk

在使用 Redux-Thunk 异步操作的 Promise 链中使用 setInterval