React Redux-对象可能是未定义的

时间:2019-06-24 15:32:38

标签: javascript reactjs typescript 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';

export const initialiseStore = (
  initialState: StoreState,
) => createStore(
  rootReducer,
  initialState,
  composeWithDevTools(applyMiddleware()),
);

我在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会产生另一个Typescript错误,该错误可能未定义globalSettings

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

1 个答案:

答案 0 :(得分:1)

错误

  

我在/redux/reducer.ts中收到以下错误:无法将类型'undefined'分配给类型'GlobalSettings'

与您定义减速器的方式

应该是

const initalState: GlobalSettingsState = {/* valid inital state */};

export default (
    state: GlobalSettingsState | undefined = initalState,
    action: GlobalSettingsAction,
): GlobalSettingsState  => {
    switch (action.type) {
        case ADD_GLOBAL_SETTINGS:
            return { ...action.payload };
        default:
            return state;
    }
}

可以在状态设置为undefined的情况下调用Reducer(以初始化状态)。因此,state参数应将undefined作为可能的值。