在Redux的世界里畅游Async Action
2023-10-14 07:48:01
在上一篇文章 Redux 入门 -- 拆分 reducer 中,阿大通过 redux 的 bindReducers 方法将水果店的业务分治成功,店铺也越做越大。以至于有顾客开始想要买一些进口的水果生鲜。阿大考虑了一下,决定继续拓展这个店铺,从事进口商品的销售。首先是顾客的需求行情调研,阿大通过一系列网络请求,获取了国外进口水果生鲜的数据,但是目前阿大还没有找到合适的方式将其展现出来。
如果按照以往的思路,阿大可能直接在组件里面发送网络请求,但是这存在一个很严重的问题,那就是组件和数据请求耦合度太高。如果下次需求变动,需要将网络请求放在其他地方执行,比如业务逻辑层,此时就需要修改所有相关的组件,这显然不是阿大想要的结果。
那有没有一种方法,可以解耦组件和数据请求呢?答案是肯定的,那就是 Redux Async Action。
什么是 Redux Async Action?
Redux Async Action,顾名思义,就是 Redux 的异步 action。它允许你在 action creator 中执行异步操作,比如发送网络请求、读取文件等。
为什么要使用 Redux Async Action?
使用 Redux Async Action 的好处有很多,比如:
- 解耦组件和数据请求 :如上所述,Redux Async Action 可以解耦组件和数据请求,使代码更加易于维护和扩展。
- 提高代码的可测试性 :由于 Redux Async Action 是在 Redux 的 action creator 中执行的,因此更容易对其进行测试。
- 更佳的性能 :Redux Async Action 可以利用浏览器的并行性,提高代码的性能。
如何使用 Redux Async Action?
使用 Redux Async Action 的步骤如下:
- 安装 Redux-Thunk 中间件 :Redux-Thunk 是一个 Redux 的中间件,它允许我们在 action creator 中执行异步操作。
npm install redux-thunk
- 将 Redux-Thunk 中间件应用到 Redux store :
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
- 创建 Redux Async Action :
import { createAction } from 'redux-actions';
const fetchFruits = createAction('FETCH_FRUITS', () => {
// 这里执行异步操作
});
- 在组件中使用 Redux Async Action :
import { useDispatch } from 'react-redux';
import { fetchFruits } from './actions';
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchFruits());
}, []);
return (
<div>
<h1>Fruits</h1>
<ul>
{fruits.map((fruit) => (
<li key={fruit.id}>{fruit.name}</li>
))}
</ul>
</div>
);
};
export default App;
Redux Async Action 的常见问题
- 如何处理 Redux Async Action 的错误?
Redux Async Action 中的错误可以通过 Redux 的 action creator 来处理。在 action creator 中,你可以捕获错误并创建一个新的 action 来表示错误。
import { createAction } from 'redux-actions';
const fetchFruits = createAction('FETCH_FRUITS', () => {
// 这里执行异步操作
if (error) {
throw error;
}
});
然后,在组件中,你可以使用 try...catch
语句来捕获错误。
import { useDispatch } from 'react-redux';
import { fetchFruits } from './actions';
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
try {
dispatch(fetchFruits());
} catch (error) {
// 这里处理错误
}
}, []);
return (
<div>
<h1>Fruits</h1>
<ul>
{fruits.map((fruit) => (
<li key={fruit.id}>{fruit.name}</li>
))}
</ul>
</div>
);
};
export default App;
- 如何取消 Redux Async Action?
Redux Async Action 可以通过 Redux 的中间件来取消。Redux-Thunk 提供了一个 cancel 方法来取消异步操作。
import { cancel } from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
// 取消异步操作
store.dispatch(cancel(actionId));
总结
Redux Async Action 是一个强大的工具,它可以帮助你解耦组件和数据请求,提高代码的可测试性和性能。但是,在使用 Redux Async Action 时,也需要特别注意错误处理和取消异步操作。