无法读取未定义的ReactJs的属性“ todos”,Redux

时间:2020-06-17 10:56:15

标签: reactjs redux

我刚刚开始熟悉Redux,但是我一直卡在这个错误上。我正在收到错误无法读取未定义的属性“ todos”,在下面的代码位于组件中。 :

const mapStateToProps = (item) => {
return {
    todos: item.todos,
    numberPerPage: item.numberPerPage,
    currentPage: item.currentPage
};
};

这是我的存储空间:

    const initialState = {
    todos: [],
    numberPerPage: 10,
    currentPage: 1
}

const reducer = (state =initialState, action) => {
    const { items, numberPerPage, currentPage } = state;
    switch (action.type) {
        case actionTypes.ADD_ITEM:
            return {
                ...state,
                todos: [
                    ...items,
                    {
                        value: action.value,
                        checked: action.checked,
                        _id: action.id,
                    },
                ],
                currentPage: Math.ceil((items.length + 1) / numberPerPage)
            };
        case actionTypes.GET_ALL:
            return {
                ...state,
                todos: action.items,
            };
    }
}

export default reducer;

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

减速器中没有默认情况,这是导致错误的原因。

最初设置化简器时,redux会分派一个@@redux/INIT action,此时化简器返回undefined,当您尝试访问状态值时会导致错误

添加默认案例以返回状态将解决此问题并解决您的问题

const reducer = (state =initialState, action) => {
    const { items, numberPerPage, currentPage } = state;
    switch (action.type) {
        case actionTypes.ADD_ITEM:
            return {
                ...state,
                todos: [
                    ...items,
                    {
                        value: action.value,
                        checked: action.checked,
                        _id: action.id,
                    },
                ],
                currentPage: Math.ceil((items.length + 1) / numberPerPage)
            };
        case actionTypes.GET_ALL:
            return {
                ...state,
                todos: action.items,
            };

        default: return state;
    }
}