0

很长一段时间以来,我一直坚持这一点,到目前为止,在线支持都没有太大帮助。我正在尝试在我的 React-Native 应用程序中使用 immer 来实现不变性。但是减速器部分给出了一个错误,说减速器“计数”在初始化期间返回未定义。我的计数减少器看起来像这样 -

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;

我怎样才能解决这个问题?

4

1 回答 1

0

从外观上看,您没有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;
      }
    }
  });
于 2019-12-28T15:08:23.923 回答