npm install --save redux-effect
经过redux中间件的方式使async方法能够在redux中使用。npm
若是你使用redux-saga,应该很是容易上手redux-effect。effect概念正是来自于saga,其自己就是一个普通的async函数,你能够在此处理一些异步逻辑,管理reducer。redux
首先咱们定义一个简易的reducer,没有特殊需求的话,reducer只作一件事,就是将action中的参数保存起来,很简单有木有。markdown
function commonReducer(state = {}, action) { switch (action.type) { case 'common/save': return { ...state, ...action.payload, }; default: return state; } }
接着定义一个简陋的effect方法,用于从服务端获取一些数据,并将其存入reducer。app
async function test ({ payload }, { dispatch, getState }) { const data = await fetch() await dispatch({ type: 'common/save', payload: data }) }
定义好reducer和effect,就能够设置store了,参考代码以下:异步
import effect from 'redux-effect'; const effects = { 'common/test': test } export const store = (initialState = {}) => { const temp = createStore( reducer, initialState, composeWithDevTools(applyMiddleware(effect(effects))), ); return temp; };
而后就能够愉快的使用dispatch一个action来完成异步操做啦。async
const { dispatch } = this.props; dispatch({ type: 'user/getUserInfo', });