redux-effect


npm install --save redux-effect

通过redux中间件的方式使async方法可以在redux中使用。

如果你使用redux-saga,应该非常容易上手redux-effect。effect概念正是来自于saga,其本身就是一个普通的async函数,你可以在此处理一些异步逻辑,管理reducer。

首先我们定义一个简易的reducer,没有特殊需求的话,reducer只做一件事,就是将action中的参数保存起来,很简单有木有。

function commonReducer(state = {}, action) {
  switch (action.type) {
      case 'common/save':
        return {
          ...state,
          ...action.payload,
        };
      default:
          return state;
  }
}

接着定义一个简陋的effect方法,用于从服务端获取一些数据,并将其存入reducer。

  • effect是一个普通的async方法。
  • 每个effect的第一个参数就是action,我一般将参数放在payload中。
  • effect的第二个参数是store对象,可以拿到dispatch和getState。
  • dispatch一个新的action,可以触发reducer,或者发起另一个effect。
  • getState则用于获取任意reducer已有的数据。
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来完成异步操作啦。

const { dispatch } = this.props;
dispatch({
 type: 'user/getUserInfo',
});
posted @ 2018-09-05 15:18  割肉机  阅读(741)  评论(0编辑  收藏  举报