Redux-thunk 源码分析
redux-thunk 的源码
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) =>
(next) =>
(action) => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
1
2
3
4
5
6
7
8
9
10
11
12
13
如何使用
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
const store = createStore(
reducer,
applyMiddleware(thunk)
)
1
2
3
4
5
6
7
8
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
function increment() {
return {
type: INCREMENT_COUNTER,
};
}
function incrementAsync() {
return (dispatch) => {
setTimeout(() => {
dispatch(increment());
}, 1000);
};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16