【问题标题】:chaining redux-actions and redux-promise-middleware链接 redux-actions 和 redux-promise-middleware
【发布时间】:2017-05-13 00:40:42
【问题描述】:

我使用 redux-actionsredux-promise-middleware 来调度操作,同时使用 TypeScript 2.1 来支持 async await

这是一个同时使用redux-actionsredux-promise-middleware 的操作

// create an async action
const fooAction = createAction('FOO', async () => {
  const { response } = await asyncFoo();
  return response;
});

// use async action
fooAction('123')

这是一个动作链的例子,只使用redux-promise-middleware

const foo = () => dispatch => {
  return dispatch({
    type: 'TYPE',
    payload: new Promise()
  })
  .then(() => dispatch(bar()));
}

redux-promise-middleware 中的链接如何与redux-actions 一起使用?

【问题讨论】:

  • 在实际项目中使用了 5 个月后,我切换到了 redux-saga。 redux-thunk 的问题是您必须将越来越多的数据作为参数传输给操作,最后,您希望将应用程序的整个状态传输到那里。 Redux-saga 默认知道这一点,并为此和其他有用的东西提供了特殊的方法。
  • 顺便说一句,您还可以使用 getState 读取状态。签名是 (dispatch, getState) => ...

标签: typescript redux redux-promise


【解决方案1】:

您必须记住,即使 async await 看起来是同步的,它在后台使用 Promise,并且无论您是否使用 awaitasync 函数将始终返回一个 Promise。

由于createAction 的第二个参数是您的有效负载创建者,因此没有什么可以阻止您使用生成的对象。

这是一个基于您的初始代码的示例:

const fakeCall = () => new Promise(resolve => {
  setTimeout(() => resolve({ response: 'ok' }), 1E3)
})

const fooAction = createAction('FOO', async () => {
  const { response } = await fakeCall()
  return response
})

const foo = () => dispatch =>
  dispatch(fooAction())
    .then(() => dispatch(bar()))

// or

const foo = () => async dispatch => {
  await dispatch(fooAction())
  dispatch(bar())
}

【讨论】:

    【解决方案2】:

    Aperçu 回答的问题是“等待”是你正在阻塞事件循环,你必须直接处理 Promises。

    “redux-promise-middleware”有一个替代方案,redux-auto 具有与 redux-promise-middleware 相同的 API,但也带有链接 reducers 调用的机制。

    你的例子看起来像:

    // UI code
    actions.data.foo()
    
    // store/data/foo.js
    export function fulfillment(data,payload){
       return data
    } fulfillment.chain = actions.x.bar
    
    export function action(payload){
        return Promise.resolve()
    }
    

    真的,就是这样。您只需要将操作分配给链属性,redux-auto 就会在 redux 生命周期中的正确位置调用它

    了解以上来源。 redux-auto 自动创建动作并根据文件结构将它们连接到 reduce。其中文件夹名称成为状态属性的名称。文件夹中的文件是要对状态的该部分执行的操作。

    这里是文档chaining action together

    【讨论】:

    • 您应该在回答中宣传 redux-auto 是您的库。
    • await 不会阻塞事件循环。就像 Aperçu 说的那样,它看起来是同步的。您的应用程序中的点击事件等内容仍然有效。 while true 会阻塞事件循环
    猜你喜欢
    • 2018-05-05
    • 2017-10-26
    • 2017-07-29
    • 2017-02-08
    • 2017-02-04
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多