Redux reducer错误 - 赋值必须是一个对象

时间:2018-02-09 09:31:25

标签: javascript reactjs react-redux

我在reducer return语句中遇到以下错误。

在此环境中,assign的源必须是一个对象。此错误是性能优化,不符合规范。

export function setCredentials(state = {}, action) {
    switch (action.type) {
        case "SET_YEAR":
            return { ...state, ...action.setYear };
        case "SET_STUDENT":
            return { ...state, ...action.setStudent };
        case "SET_GROUP":
            return { ...state, ...action.setGroup };
        default:
            return state;
    }
}

行动创作者:

export const setYear = int => ({
    type: "SET_YEAR",
    setYear: int
});

export const setGroup = int => ({
    type: "SET_GROUP",
    setGroup: int
});

export const setStudent = int => ({
    type: "SET_STUDENT",
    setStudent: int
});

我正在尝试创建以下状态:

{
      setCredentials: {
                 setYear: 20,
                 setStudent:10,
                 setGroup: 10
      }
}

有什么想法吗?

减速/ index.js

import { combineReducers } from "redux";
import {
    setCredentials,
    fetchCategories,
    eventsForMonth,
    fetchEvents
} from "./events";

import { hasErrored, isLoading } from "./loader";

import navigationReducer from "./navigationReducer";
const rootReducer = combineReducers({
    fetchEvents,
    navigationReducer,
    hasErrored,
    eventsForMonth,
    isLoading,
    fetchCategories,
    setCredentials
});

export default rootReducer;

商店:

import rootReducer from "../reducers";

const initialState = {
    hasErrored: false,
    isLoading: true,
    fetchEvents: {},
    fetchCategories: [],
    setCredentials: {}
};

const reduxLogger = createLogger();

const store = createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk, reduxLogger)
);

export default store;

1 个答案:

答案 0 :(得分:1)

在你的减速器中,你试图破坏价值,而不是对象。看到这个提议的改变,你会理解它:

export function setCredentials(state = {}, action) {
    switch (action.type) {
        case "SET_YEAR":
            return { ...state, setYear: action.setYear };
        case "SET_STUDENT":
            return { ...state, setStudent: action.setStudent };
        case "SET_GROUP":
            return { ...state, setGroup: action.setGroup };
        default:
            return state;
    }
}