错误:初始化期间,Reducer“ assetsReducer”返回未定义。如果传递给减速器的状态未定义,则必须显式返回初始状态。初始状态可能未定义。如果您不想为此减速器设置值,则可以使用null而不是undefined。
在我的ReactJS应用中,我有2个reducer / action(assets
和board
)。
在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)
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;
}
};
答案 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
定义自己的初始状态值(如果需要在其他地方引用,则将其单独导出)。