如何在打字稿中为redux reducer设置初始状态?

时间:2020-05-28 03:37:36

标签: typescript redux redux-reducers

我收到此TypeScript错误属性,类型'(state:ErrorType | undefined,action:ErrorActionType)=> ErrorType'不存在属性'hasError'。我认为它抱怨要为reducer设置initialState。

import { ErrorType, ErrorActionType } from '../actions';
import { ActionTypes } from '../types';

export const errorReducer = (
  state: ErrorType = { hasError: false, errorMessage: '' },
  action: ErrorActionType
) => {
  switch (action.type) {
    case ActionTypes.setError:
      return action.payload;
    default:
      return state;
  }
};

这是我的动作

import { Dispatch } from 'redux';
import { ActionTypes } from '../types';

export interface ErrorType {
  hasError: boolean;
  errorMessage: string;
}
export interface ErrorActionType {
  type: ActionTypes.setError;
  payload: ErrorType;
}

export const setError = (hasError: boolean, errorMessage: string) => {
  return (dispatch: Dispatch) => {
    dispatch<ErrorActionType>({
      type: ActionTypes.setError,
      payload: { hasError, errorMessage },
    });
  };
};

还有我的reducer.index

import { combineReducers } from 'redux';
import { errorReducer } from './error';
import { loadingReducer } from './loading';
import { newsReducer } from './news';
import { schoolsReducer } from './schools';

import { StoreStateType } from '../types';

export const reducers = combineReducers<StoreStateType>({
  isLoading: loadingReducer,
  hasError: errorReducer.hasError,
  errorMessage: errorReducer.errorMessage,
  news: newsReducer,
  schools: schoolsReducer,
});

这是应用状态类型

export interface StoreStateType {
  isLoading: boolean;
  hasError: boolean;
  errorMessage: string;
  news: NewsType[];
  schools: SchoolType[];
}

0 个答案:

没有答案