【问题标题】:how can i replace my redux actions and use create actions library?如何替换我的 redux 操作并使用创建操作库?
【发布时间】:2019-12-02 09:20:43
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: reactjs react-native redux redux-saga redux-actions


    【解决方案1】:

    查看 redux-action docs,动作定义应如下所示:

    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: {...} });
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 2020-06-08
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      相关资源
      最近更新 更多