【问题标题】:Redux.js: catching malformed actions?Redux.js:捕获格式错误的操作?
【发布时间】:2017-04-14 09:54:08
【问题描述】:

是否有最佳实践/推荐的方法来断言 redux 操作格式正确?我是一个相当菜鸟的 JavaScript 程序员(从 20 年的 C++/Java/C# 开始)并且由于缺乏强类型而被抛弃。

我要解决的具体用例是:

1.使用 React + Redux "ToDo" 应用 (http://redux.js.org/docs/basics/ExampleTodoList.html)

2.使用动作创建器:

export function toggleTodo(index) {
  return { type: TOGGLE_TODO, index }
}

3.带reducer代码sn-p:

case TOGGLE_TODO:
  if (state.id !== action.id) {
    return state
  }

请注意,indexid 不匹配。但是,他们应该有 - 这是一个错误。这花了我 30 分钟来诊断,我只能想象更大的应用程序。

【问题讨论】:

标签: javascript reactjs redux react-redux


【解决方案1】:

您是否考虑过创建一个表示 Action 类型的 Class,然后让它处理验证,就像这样...

class ToggleAction {
   constructor(o) {
     if (
       typeof o === 'object' &&
       typeof o.type === 'string' &&
       typeof o.id === 'number'
     ) {
       this.type = "TOGGLE_TODO"; 
       this.id = o.id
     } else {
       throw new Error('Invalid ToggleAction');
     }
   }

   toObject() {
     return { type: this.type, id: this.id };
   }
}

然后你可以在动作创建器中像这样使用它......

export function toggleTodo(index) {
  return new ToggleAction({ id: index }).toObject();
}

像这样在减速器中...

case TOGGLE_TODO:
  const toggleAction = new ToggleAction(action)
  if (state.id !== toggleAction.id) {
    return state
  }

如果一切顺利,您可以创建一个生成 ActionType 类的 ActionFactory。

编辑:我创建了一个名为redux-action-validatornpm module,其中包含描述如何安装和使用它的自述文件。

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2021-07-07
    • 2018-11-20
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多