【问题标题】:Can action creator be a class with action methods动作创建者可以是具有动作方法的类吗
【发布时间】:2017-04-14 15:51:59
【问题描述】:

一般在 Redux (thunk) 中,action creators 是静态方法。但是我有一个特殊的场景,动作创建者需要对不同的端点进行异步调用。一种方法是传入一个标志来确定要转到哪个端点:

function _getEndPoint(isHouse) {
  return isHouse ? 'house' : 'flat';
}

export function post(model, isHouse = false) {
  return (dispatch, getState) => {
    dispatch({
      types: [POST, POST_SUCCESS, POST_FAILED],
      promise: (client) => client.post(`${_getEndPoint(isHouse)}`, {
        data: model,
      }),
    });
  };
}

但是有没有办法创建一个类说Propertypost 作为一个公共方法,用作操作方法。那么当我实例化Property 类时,我定义了属性的类型并在创建时设置了正确的端点?

来自 C# 背景,我也想知道是否可以使用泛型或继承之类的东西来解决这个问题。

另外,当我读到 Redux 更倾向于函数式编程时,尝试使用类创建操作方法是否是一种好习惯。

【问题讨论】:

    标签: reactjs redux reactjs-flux redux-thunk


    【解决方案1】:

    如果您必须调用不同的端点(异步或非异步) - 这些是不同的操作。假设您要处理错误。通用类型POST_FAILED 不会告诉您哪个资源失败了。如果你想根据它改变状态树怎么办?如果应该以不同的方式处理不同的类型怎么办?函数式方法POST_OF_SOMETHING_FAILED 更适合这里。小功能做他们的小事。否则你将不得不使用复杂的if 块。

    您可以实现某种动作生成器来消除代码重复,而不是使用类和继承。例如,如果您想创建共享 CRUD 操作,创建操作可能如下所示:

    /actions/generators/create.js

    import fetch from 'isomorphic-fetch';
    
    
    function requestCreateItem(modelName) {
      return {
        type: `CREATE_${modelName.toUpperCase()}_REQUEST`,
      };
    }
    
    function receiveCreateItem(modelName, item) {
      return {
        type: `CREATE_${modelName.toUpperCase()}_SUCCESS`,
        item,
        receivedAt: Date.now(),
      };
    }
    
    function catchCreateItemError(modelName, error) {
      return {
        type: `CREATE_${modelName.toUpperCase()}_ERROR`,
        error,
        receivedAt: Date.now(),
      };
    }
    
    function createItem(modelName) {
      return (dispatch) => {
        dispatch(requestCreateItem(modelName));
    
        return fetch(`/${modelName}s`, {
          method: 'POST',
          credentials: 'same-origin',
        }).then(response => response.json()).then(json => {
          if (json.error) {
            dispatch(catchCreateItemError(modelName, json.error));
          } else {
            dispatch(receiveCreateItem(modelName, json));
          }
        }).catch(error => {
          dispatch(catchCreateItemError(modelName, error));
        });
      };
    }
    
    
    export default function create(modelName) {
      return () => createItem(modelName);
    }
    

    您可以在操作索引文件中使用它作为构造函数。

    /actions/index.js

    import create from './generators/create';
    const createBot = create('bot');
    export const botActions = { createBot };
    

    这是主要思想。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多