首页 文章

使用redux存储规范化数据

提问于
浏览
2

我希望我的Reducer能够在状态中填充根对象,而不依赖于它们操作的状态片段 .

我发现很多页面都解释了normalizr有多精彩,但没有人解释存储这个规范化数据的位置和方法 .

问题是:

  • am我想做一些与众不同的错误吗?

  • 如何修改根状态对象中的状态,因为reducers仅对数据片进行操作 .

所以视频减速机:

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

应该不仅填充 state.videos (带有一个视频ID数组),而且还要填充带有规范化数据的 state.database.videos (以及其他键,如果视频包含其他实体) .

1 回答

  • 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);
    }
    

相关问题