Reducer 在初始化期间返回 undefined

Reducer returned undefined during initialization

我长期坚持这个,none到目前为止的在线支持帮助很大。 我正在尝试在我的 React-Native 应用程序中使用 immer 来实现不变性。但是reducer部分给出了一个错误,说reducer "count" returned undefined during initialization。 我的 count reducer 看起来像这样 -

import produce from "immer";
import {
    INCREMENT,
    DECREMENT,
} from '../action/index.js';

const INITIAL_STATE = {
    count: 0,
};

const countReducer = (state, action) =>
    produce(state, draft => {
        switch (action.type) {
            case INCREMENT: {
                draft = draft + 1;
                break;
            }
            case DECREMENT: {
                draft = draft - 1;
                break;
            }
        }
});

export default countReducer;

我的 rootReducer 是 -

import {combineReducers} from 'redux';
import countReducer from './countReducer.js';
const rootReducer = combineReducers({
  count: countReducer,
});
export default rootReducer;

我该如何解决这个问题?

从外观上看,您没有在代码中的任何地方使用 INITIAL_STATE

我没用过 immer,但通常你会像这样初始化你的状态

const reducer = (state = initialState, action) => {...}

所以我想你会想做这样的事情:

const INITIAL_STATE = {
  count: 0
};

const countReducer = (
  state = INITIAL_STATE, // initialises state
  action
) =>
  produce(state, draft => {
    switch (action.type) {
      case INCREMENT: {
        draft = draft + 1;
        break;
      }
      case DECREMENT: {
        draft = draft - 1;
        break;
      }
    }
  });