使用combinReducers时出错,“错误:初始化期间未定义的Reducer“ assetsReducer”返回。

时间:2019-02-19 21:15:26

标签: javascript reactjs typescript redux

  

错误:初始化期间,Reducer“ assetsReducer”返回未定义。如果传递给减速器的状态未定义,则必须显式返回初始状态。初始状态可能未定义。如果您不想为此减速器设置值,则可以使用null而不是undefined。

在我的ReactJS应用中,我有2个reducer / action(assetsboard)。

在store.ts文件中,我像这样使用combineReducers

import { applyMiddleware, createStore, combineReducers } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'

import { IinitialState } from './shared/types'
// import reducer from './reducers/assets/'
import assetsReducer from './reducers/assets'
import boardReducer from './reducers/board'

const rootReducer = combineReducers({
  assetsReducer,
  boardReducer
});

export const defaultInitialState = {
  assets: [],
  portfolio: [],
  loading: false,
  overlay: false
};

console.log('rootReducer', rootReducer);

export function initializeStore(initialState: IinitialState = defaultInitialState) {
  return createStore(
    rootReducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunkMiddleware))
  )
}

这应该是正确的,但是当我在本地主机上刷新应用程序时,出现以下打字错误和上面的控制台错误。

Type 'IinitialState' has no properties in common with type 
     

'DeepPartial <{assetReducer:   {资产:任何; loading:布尔值;投资组合:从不[]; overlay:布尔值; }; boardReducer:{overlay:any;资产:从不[];投资组合:从不[]; loading:布尔值; }; }>'。ts(2559)

enter image description here


assetsReducer:

import { Actions } from '../actions/assets'
import { defaultInitialState } from '../store'

export default (state = defaultInitialState, action: any) => {
  switch (action.type) {
    case Actions.GET_ALL_ASSETS: {
      const { assets } = action;
      return {
        ...state,
        assets,
        loading: false
      };
    }

    default:
      return state;
  }
};

boardReducer

import { Actions } from '../actions/board'
import { defaultInitialState } from '../store'

export default (state = defaultInitialState, action: any) => {
  switch (action.type) {
    case Actions.SET_OVERLAY_STATE: {
      const { overlay } = action;
      return {
        ...state,
        overlay
      };
    }

    default:
      return state;
  }
};

2 个答案:

答案 0 :(得分:1)

您的初始状态不正确。您的初始状态应如下所示:

export const defaultInitialState = {
  assetsReducer: {assets: [], loading: false, portfolio: [], overlay: false},
  boardReducer: {assets: [], loading: false, portfolio: [], overlay: false},
}

有关更多信息,请参见Redux Docs

答案 1 :(得分:1)

除其他答复外,您似乎有一个循环参考问题。

store.ts导入assetsReducer.ts,但是assetsReducer尝试导入store以获得其初始默认状态值。

因此,在加载assetsReducer.ts时,store.ts尚未完成评估,并且defaultInitialState未定义。

您应该重新组织事情,以便不再有循环引用。最简单的方法是让assetsReducer.ts定义自己的初始状态值(如果需要在其他地方引用,则将其单独导出)。

相关问题