1

我正在寻找可以减少 redux 样板的 redux 库,最近我发现了 reduxsouce 和 redux-actions,它们有助于减少 action 对象代码的重写。在我之前的所有动作定义项目中,我将为所有动作创建一个文件,动作看起来像这样

export function requestInit() {
  return {
    type: types.REQUEST_INIT,
    payload: {
      loading: true,
    },
  };
}

现在,如果我想删除动作定义并切换到“createaction”,我该如何用 redux-actions 中的 createaction 方法替换它?

另外我如何处理或“放置”来自 saga 的其他失败或成功操作(生成器函数)?

4

1 回答 1

0

查看 redux-action文档,操作定义应如下所示:

import { createAction, handleAction } from 'redux-actions';
const defaultState = { loading: false };

export const requestInit = createAction(types.REQUEST_INIT); // creates an action creator

// Define your reducer here, as second argument. 
// First argument is the action type, third is defaultState
handleAction(
  types.REQUEST_INIT,
  (state, action) => ({
    loading: action.payload.loading
  }),
  defaultState
);
...
// in saga.js or other place you want to use the action
requestInit({ loading: true }); 

以同样的方式,您可以添加其他操作来处理您的请求。调度和处理错误应该与普通操作完全相同,即:

yield put({ type: response, payload: {...} });

希望这会有所帮助。

于 2019-12-02T10:18:17.750 回答