Redux-thunk
- redux-thunk 下载
npm install redux-thunk
- 引入 redux-thunk
import thunk from 'redux-thunk';
- 注册 redux-thunk
import { applyMiddleware } from 'redux';createStore(rootReducer, applyMiddleware(thunk));
- 使用 redux-thunk
const loadPosts = () => async dispatch => {const posts = await axios.get('/api/posts').then(res => res.data);dispatch({type: LOADPOSTSUCCESS,payload: posts})}
- redux-thunk 源码
判断传入的action是异步函数还是对象,如果是函数先执行函数,函数执行结束之后再传入reducer中。export default ({dispatch}) => next => action => {if (typeof action === 'function') {return action(dispatch);}next(action);}
