React redux - 对象可能是“未定义的”

我收到一个 Typescript 错误,我在 Redux 中使用的对象可能未定义,即使我没有说它的类型可以未定义或在任何地方将其设置为未定义。


/redux/globalSettings/actions.ts


import { ADD_GLOBAL_SETTINGS } from '../../config/actions';

import { AddGlobalSettingsAction } from './types';

import GlobalSettings from '../../typings/contentful/GlobalSettings';


export const addGlobalSettings = (payload: GlobalSettings): AddGlobalSettingsAction => ({

  type: ADD_GLOBAL_SETTINGS,

  payload,

});

/redux/globalSettings/reducers.ts


import { ADD_GLOBAL_SETTINGS } from '../../config/actions';

import { GlobalSettingsAction, GlobalSettingsState } from './types';


export default (

  state: GlobalSettingsState,

  action: GlobalSettingsAction,

): GlobalSettingsState  => {

  switch (action.type) {

    case ADD_GLOBAL_SETTINGS:

      return { ...action.payload };

    default:

      return state;

  }

}

/redux/globalSettings/types.ts


import { ADD_GLOBAL_SETTINGS } from '../../config/actions';

import GlobalSettings from '../../typings/contentful/GlobalSettings';


export type GlobalSettingsState = GlobalSettings;


export interface AddGlobalSettingsAction {

  payload: GlobalSettings;

  type: typeof ADD_GLOBAL_SETTINGS;

}


export type GlobalSettingsAction = AddGlobalSettingsAction;

/redux/reducer.ts


import { combineReducers } from 'redux';

import globalSettings from './globalSettings/reducers';


const rootReducer = combineReducers({

  globalSettings,

});


export type StoreState = ReturnType<typeof rootReducer>;


export default rootReducer;

/redux/index.ts


import { applyMiddleware, createStore } from 'redux';

import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';

import rootReducer, { StoreState } from './reducer';


我通过在next-redux-wrapper我的_app.js页面导出时使用NPM 包(一个 React HOC)在我的 NextJS 项目中使用它,如下所示:


export default withRedux(initialiseStore)(Page);

我在/redux/reducer.ts得到一个错误:Type 'undefined' is not assignable to type 'GlobalSettings'。


如果我globalSettings在我的一个页面上使用redux 状态,访问globalSettings.fields.navigationLinks会创建另一个globalSettings可能未定义的Typescript 错误。


让我发疯,我在这里做错了什么?


饮歌长啸
浏览 386回答 1
1回答

紫衣仙女

错误我在 /redux/reducer.ts 中收到一个错误:类型 'undefined' 不可分配给类型 'GlobalSettings'与您如何定义减速器有关它应该是const initalState: GlobalSettingsState = {/* valid inital state */};export default (&nbsp; &nbsp; state: GlobalSettingsState | undefined = initalState,&nbsp; &nbsp; action: GlobalSettingsAction,): GlobalSettingsState&nbsp; => {&nbsp; &nbsp; switch (action.type) {&nbsp; &nbsp; &nbsp; &nbsp; case ADD_GLOBAL_SETTINGS:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return { ...action.payload };&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return state;&nbsp; &nbsp; }}可以在状态设置为未定义(以初始化状态)的情况下调用 Reducer。所以state论点应该具有undefined尽可能的价值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript