如何用Redux实现异步action的解决方案?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1162个文字,预计阅读时间需要5分钟。
如果没有中间件,`store.dispatch` 只能接收一个普通对象作为 action。在处理异步 action 时,我们需要在异步回调或 promise 的 then 函数中,或 async 函数的 await 之后调用 `dispatch`。例如:
+ `dispatch({ type: 'before-load' }).then(()=> fetch('ht'))`;
如果没有中间件,store.dispatch只能接收一个普通对象作为action。在处理异步action时,我们需要在异步回调或者promise函数then内,async函数await之后dispatch。
dispatch({ type:'before-load' }) fetch('myapi.com/${userId}').then({ response =>dispatch({ type:'load', payload:response }) })
这样做确实可以解决问题,特别是在小型项目中,高效,可读性强。 但缺点是需要在组件中写大量的异步逻辑代码,不能将异步过程(例如异步获取数据)与dispatch抽象出来进行复用。而采用类似redux-thunk之类的中间件可以使得dispatch能够接收不仅仅是普通对象作为action。
本文共计1162个文字,预计阅读时间需要5分钟。
如果没有中间件,`store.dispatch` 只能接收一个普通对象作为 action。在处理异步 action 时,我们需要在异步回调或 promise 的 then 函数中,或 async 函数的 await 之后调用 `dispatch`。例如:
+ `dispatch({ type: 'before-load' }).then(()=> fetch('ht'))`;
如果没有中间件,store.dispatch只能接收一个普通对象作为action。在处理异步action时,我们需要在异步回调或者promise函数then内,async函数await之后dispatch。
dispatch({ type:'before-load' }) fetch('myapi.com/${userId}').then({ response =>dispatch({ type:'load', payload:response }) })
这样做确实可以解决问题,特别是在小型项目中,高效,可读性强。 但缺点是需要在组件中写大量的异步逻辑代码,不能将异步过程(例如异步获取数据)与dispatch抽象出来进行复用。而采用类似redux-thunk之类的中间件可以使得dispatch能够接收不仅仅是普通对象作为action。

