首页 > 解决方案 > 如何在没有初始状态的情况下使用 combineReducers 创建 Redux 存储

问题描述

我有以下 Redux 商店:

import {createStore} from 'redux';
import rootReducer from './reducers';

export function configureStore() {
  const store = createStore(rootReducer);

  return store;
};

const store = configureStore()
export default store;

这是rootReducer创建的combineReducers

import {combineReducers} from 'redux';
import application from '../features/application/reducers';

const rootReducer = combineReducers({
  application,
});

export default rootReducer;

这是提供者的创建:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import store from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

问题是我收到以下错误:

Error: The slice reducer for key "application" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.

我检查了此文档,但找不到解决问题的方法。

编辑

我看到问题可能与 webpack 有关,但我不知道:

这是applicationreducer的代码:

import { ActionInterface } from '../generals';
import {
  FETCH_APPLICATION_COMPOSITE_SUCCESS,
  SET_CURRENT_APPLICATION_COMPONENT
} from './actions';

const INIT_STATE = {
  applicationComposite: null,
  currentApplicationComponent: null
}

export default (state=INIT_STATE, action: ActionInterface) => {
  switch(action.type) {
    case FETCH_APPLICATION_COMPOSITE_SUCCESS: {
      return {
        ...state,
        //@ts-ignore: Object is possibly 'undefined'
        applicationComposite: action.payload.applicationComposite
      }
    }
    case SET_CURRENT_APPLICATION_COMPONENT: {
      return {
        ...state,
        //@ts-ignore: Object is possibly 'undefined'
        currentApplicationComponent: action.payload.applicationComponent
      }
    }
  }
}

在此处输入图像描述

标签: reactjsreact-redux

解决方案


您需要将默认返回添加到减速器

import { ActionInterface } from '../generals';
import {
  FETCH_APPLICATION_COMPOSITE_SUCCESS,
  SET_CURRENT_APPLICATION_COMPONENT
} from './actions';

const INIT_STATE = {
  applicationComposite: null,
  currentApplicationComponent: null
}

export default (state=INIT_STATE, action: ActionInterface) => {
  switch(action.type) {
    case FETCH_APPLICATION_COMPOSITE_SUCCESS: {
      return {
        ...state,
        //@ts-ignore: Object is possibly 'undefined'
        applicationComposite: action.payload.applicationComposite
      }
    }
    case SET_CURRENT_APPLICATION_COMPONENT: {
      return {
        ...state,
        //@ts-ignore: Object is possibly 'undefined'
        currentApplicationComponent: action.payload.applicationComponent
      }
    }
    default: return state;
  }
}

推荐阅读