如何将redux处理异步action的解决方案改写成长尾?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1179个文字,预计阅读时间需要5分钟。
如果不存在中间件,`store.dispatch` 只能接收一个普通对象作为 action。在处理异步 action 时,我们通常需要在异步回调或 Promise 的 `then` 方法中或 `async` 函数的 `await` 语句后调用 `dispatch`。例如:
javascriptdispatch({ type: 'before-load' });fetch('http://example.com/data') .then(response=> response.json()) .then(data=> dispatch({ type: 'load-success', payload: data }));
如果没有中间件,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。
本文共计1179个文字,预计阅读时间需要5分钟。
如果不存在中间件,`store.dispatch` 只能接收一个普通对象作为 action。在处理异步 action 时,我们通常需要在异步回调或 Promise 的 `then` 方法中或 `async` 函数的 `await` 语句后调用 `dispatch`。例如:
javascriptdispatch({ type: 'before-load' });fetch('http://example.com/data') .then(response=> response.json()) .then(data=> dispatch({ type: 'load-success', payload: data }));
如果没有中间件,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。

