2016-11-30 64 views
0

是否有一個最佳實踐/推薦的方式來斷言redux行爲是否良構?我是一個相當不喜歡的JavaScript程序員(從20年的C++/Java/C#開始),並且由於缺乏強大的輸入而被拋棄。Redux.js:捕獲格式錯誤的操作?

具體我試圖地址的使用情況是:

1.使用陣營+終極版 「待辦事項」 應用程序(http://redux.js.org/docs/basics/ExampleTodoList.html

2.使用行動的創建者:

​​

3.with reducer code snippet:

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

請注意,索引id不匹配。但是,他們應該有 - 這是一個錯誤。這花了我30分鐘來診斷,我只能想象更大的應用程序。

+1

我創建了一個GitHub庫,它有一個redux-action-validator基類。 README有關於實現的更多信息:https://github.com/michael-martin-al/redux-action-validator –

+0

這很酷! – Malachi

回答

1

你有沒有考慮創建表示動作類型的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 
    } 

如果所有的作品你可以創建一個ActionFactory來生成ActionType類。

編輯:我創建了一個npm module調用redux-action-validator與README描述如何安裝和使用它。