一、安装
yarn add redux-thunk
// 或
npm install --save redux-thunk
二、使用
import { createStore, applyMiddleware } from "redux";
import * as loginActions from "./action/login";
import reducer from "./reducer";
import logger from "redux-logger";
import thunk from "redux-thunk";
// 创建仓库
const store = applyMiddleware(thunk, logger)(createStore)(reducer);
三、为什么要使用redux-thunk?
redux中的action都必须要是一个平面对象,所以就不能有任何的副作用,redux-thunk就是为了解决这一问题,使用redux-thunk中间件后,允许action返回一个函数,这个函数是允许有副作用的
例如:
写一个带有副作用的action:
export function setTime(payload) {
return function () {
setTimeout(() => {
console.log("定时器");
}, 1000);
};
}
如果没有使用redux-thunk会直接报错显示action必须是一个平面对象
import { createStore, applyMiddleware } from "redux";
import * as loginActions from "./action/login";
import reducer from "./reducer";
import logger from "redux-logger";
import thunk from "redux-thunk";
// 创建仓库
const store = applyMiddleware(logger)(createStore)(reducer);
store.dispatch(loginActions.setTime());
使用了redux-thunk中间件后正常运行
四、redux-thunk运行原理
redux-thunk中间件一般放在第一个,因为它在接收action时如果发现action不是一个平面对象,那么它就不会传递给下一个中间件,它会直接将这个函数运行,如果action是一个平面对象它才会往后传递
五、redux-thunk原理
redux-thunk会返回给action3个参数
1.dispatch:store的dispatch
2.getState:store的getState
3.extraArgument:用户传入的参数
源码:
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
// 如果当前的action是一个函数直接调用该函数
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
// 如果当前的action是一个平面对象,传递个下一个中间件
return next(action);
};
}
const thunk = createThunkMiddleware();
// 可以使用withExtraArgument传入一个参数
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;