嵌套的redux状态 - 获取错误“无法读取未定义的属性”

时间:2017-12-20 16:48:53

标签: reactjs redux react-redux

我正在尝试实现组件命名空间,以便我可以在不同的工作流程中重用动作和减少器。我有嵌套的状态结构。以下是我的根减速器的外观

const rootReducer = combineReducers({
session: SessionReducer,
posts: PostsReducer,
form: formReducer,
employees : {
    currentPage : currentPageReducer('employees'),
    itemProperties : itemPropertiesReducer('employees'),
    items : items('employees'),
    itemsPerPage : perPageReducer('employees'),
    sortingProperty : sortReducer('employees'),
    filters : filtersReducer('employees')
}});

在组件中,状态如下所示

function mapStateToProps(state, ownProps) {  
let myState = state[ownProps.namepspace];
return {
    currentPage: myState.currentPage,
    itemProperties: myState.itemProperties,
    items: myState.items,
    itemsPerPage: myState.itemsPerPage,
    sortingProperty: myState.sortingProperty,
    filters: myState.filters
};}

命名空间作为ownProps传递给组件,如下所示

<DataTable namespace='employees' />

以下是示例操作

export const REFRESH_FILTERS = 'REFRESH_FILTERS'; 
export function refreshFilters(namespace) { 
return { 
  type: `${namespace}/${REFRESH_FILTERS}`
};}

这就是我的减速机的外观

let filtersReducer = (namespace) => (state = initialState, action) => {
switch (action.type) {      
    case `${namespace}/${REFRESH_FILTERS}`:
        return initialState;
    default:
        return state;
}
};

当我尝试访问状态“无法读取未定义的属性currentPage”时,我在mapStateToProps函数中收到错误消息。我错过了什么吗?这不是访问嵌套状态属性的正确方法吗?

1 个答案:

答案 0 :(得分:2)

你不能像这样嵌套减速器。或者,您需要自己调用它们或使用combineReducers函数来组合它们。试试这个根减速器,

const rootReducer = combineReducers({
    session: SessionReducer,
    posts: PostsReducer,
    form: formReducer,
    employees : combineReducers({
         currentPage : currentPageReducer('employees'),
         itemProperties : itemPropertiesReducer('employees'),
         items : items('employees'),
         itemsPerPage : perPageReducer('employees'),
         sortingProperty : sortReducer('employees'),
         filters : filtersReducer('employees')
    })
});

编辑:只是为了整理,您的代码中有两个问题。一个是错字(@brub的好捕获),以及combineReducers中的问题