本文主要介绍了在 Redux 中使用 redux-thunk 进行异步操作。
如果对 Redux 尚不熟悉,建议先看我的上一篇博客:Redux 基础教程以及结合 React 使用方式。
最下方贴上了 applyMiddleware 和 redux-thunk 的实现源码,有兴趣的同学可以看一看。只能用两个字来形容:优秀。
在项目中引入
-
安装插件
$ npm install redux-thunk -S;
使用 commonJs 方式引入时要注意,这样引入才可以正常使用:const thunk = require(‘redux-thunk’).default
-
在创建 store 时引入 redux-thunk
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; // 创建 store // applyMiddleware,在 Redux 中使用中间件时,就需要使用 applyMiddleware() 这个函数进行包裹 const store = createStore(reducer, applyMiddleware(thunk));
-
在 action 中的书写方式
// 异步请求成功会用到的同步 action 创建函数 function actionSuccess(msg) { return { type: 'SUCCESS', message: msg } } // 异步请求失败会用到的同步 action 创建函数 function actionError() { return { type: 'ERRO