是否有最佳实践/推荐方法来断言 redux 操作格式良好?我是一个相当菜鸟的 JavaScript 程序员(有 20 年的 C++/Java/C# 经验),并且因缺乏强类型而感到困惑。
具体来说,我试图解决的用例是:
1.使用 React + Redux“ToDo”应用程序 ( http://redux.js.org/docs/basics/ExampleTodoList.html )
2.使用 Action 创建器:
export function toggleTodo(index) {
return { type: TOGGLE_TODO, index }
}
3.withreducer代码片段:
case TOGGLE_TODO:
if (state.id !== action.id) {
return state
}
请注意,index 和 id 不匹配。然而,他们应该有——这是一个错误。我花了 30 分钟来诊断,我只能想象更大的应用程序。
最佳答案
您是否考虑过创建一个代表 Action 类型的类,然后让它处理验证,就像这样......
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 };
}
}
然后你可以在 Action 创建器中像这样使用它......
export function toggleTodo(index) {
return new ToggleAction({ id: index }).toObject();
}
像这样在 reducer 中......
case TOGGLE_TODO:
const toggleAction = new ToggleAction(action)
if (state.id !== toggleAction.id) {
return state
}
如果一切顺利,您可以创建一个生成 ActionType 类的 ActionFactory。
编辑:我创建了一个 npm module名为 redux-action-validator
,其中包含描述如何安装和使用它的自述文件。
关于javascript - Redux.js : catching malformed actions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882204/