首页 文章

链接redux-actions和redux-promise-middleware

提问于
浏览
5

我使用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 一起使用?

2 回答

  • 0

    你必须要记住,即使 async await 看起来是同步的,它也会使用Promise,并且 async 函数将始终返回Promise,无论你是否使用 await .

    由于 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())
    }
    
  • 3

    Aperçu回答的问题是“await”是你阻塞事件循环而你必须直接处理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会根据文件结构自动创建操作并将它们连接起来 . 文件夹名称成为状态属性的名称 . 文件夹中的文件是要对状态的该部分执行的操作 .

    这是文档chaining action together

相关问题