2016-04-12 51 views
2

我希望我的reducer能夠在狀態中填充一個根對象,而與它所在的狀態片無關。使用redux存儲規範化的數據

我發現很多頁面解釋normalizr有多美妙,但沒有人解釋在何處以及如何存儲這些規範化的數據。

的問題是:

  1. 上午我試圖做一些不尋常的,錯了嗎?

  2. 我該如何修改根狀態對象中的狀態,因爲減速器只能操作一部分數據。

所以視頻減速機:

const videos = (state, action) => { 
    switch (action.type) { 
    case 'LOAD_VIDEOS': { 
     return .... 
    } 
    } 
} 

應該填充不僅state.videos(視頻ID的數組),也state.database.videos(和其他按鍵,以及如果視頻中包含其他實體)與歸一化數據。

回答

2

如果您的減速機需要在多於一個狀態下工作,請將其設爲整個狀態。

如果您使用combineReducers(),你可以用它使你保持減速相結合的優勢,你仍然可以有一個對全州工作的減速機:

function somePartOfState(state, action) { 
    // ... 
} 
function otherPartOfState(state, action) { 
    // ... 
} 
function fullState(state, action) { 
    // ... 
} 

const combined = combineReducers({ 
    somePartOfState, 
    otherPartOfState 
}); 

export function rootReducer(state, action) { 
    // call the combined reducers, 
    // then pass the resulting state to the fullState reducer 
    return fullState(combined(state, action), action); 
} 
+0

尼斯的答案。其實,我沒有特別的要求,只是一個簡單的應用程序,所以我想知道爲什麼這種方法沒有在任何博客,文檔或教程廣告。 – agori

+0

謝謝。實際上,[官方文檔](http://redux.js.org/docs/basics/Reducers.html)首先是一個簡單的函數,然後再轉到組合reducer,並解釋combineReducers()只是一個幫手:「所有組合的Reader ()會產生一個函數,它會根據鍵的狀態選擇狀態切片來調用你的reducer,然後再將它們的結果組合到一個對象中,這不是魔術。 –