使用Typescript设置ContextApi和useReducer时出现“没有重载匹配此调用”错误

问题描述

我在使用上下文API设置reducer时遇到问题。控制台中的错误指向化简文件。我不知道发生了什么,因为初始状态具有与reducer状态的类型NewsstateContextType 相同的属性

No overload matches this call.
  Overload 1 of 5,'(reducer: ReducerWithoutAction<any>,initializerArg: any,initializer?: undefined): [any,dispatchWithoutAction]',gave the following error.
    Argument of type '(state: NewsEntryResponse,action: Action) => NewsEntryResponse | { state: NewsEntryResponse; }' is not assignable to parameter of type 'ReducerWithoutAction<any>'.
  Overload 2 of 5,'(reducer: (state: NewsEntryResponse,action: Action) => NewsEntryResponse | { state: NewsEntryResponse; },initialState: never,initializer?: undefined): [...]',gave the following error.
    Argument of type '{ count: number; prevIoUs: string; next: string; results: never[]; }' is not assignable to parameter of type 'never'.

Reducer看起来像这样

export const newsReducer = (state: NewsstateContextType,action: Action) => {
  //console.log('reducer state',state);
  switch (action.type) {
    case SET_NEWS:
      return action.payload;
    case ADD_NEWS:
      return { ...state,results: [...state.results,action.payload] };
    default:
      return { state };
  }
};

类型


interface NewsEntryResponse {
  count: number;
  prevIoUs: string | null;
  next: string | null;
  results: Array<NewsEntryResult>;
}
export type NewsstateContextType = NewsEntryResponse;

export type Action = AddNewsAction | SetNewsAction;
export type AddNewsAction = { type: typeof ADD_NEWS; payload: NewsEntryResult };
export type SetNewsAction = { type: typeof SET_NEWS; payload: NewsEntryResponse };


控制器

export const NewsController = ({ children }: { children: React.ReactNode }) => {
  const INITIAL_STATE = { count: 0,prevIoUs: '',next: '',results: [] };
  const [state,dispatch] = useReducer(newsReducer,INITIAL_STATE);
  //console.log('News Controller state',state);

  return (
    <NewsstateContext.Provider value={state}>
      <NewsdispatchContext.Provider value={dispatch}>{children}</NewsdispatchContext.Provider>
    </NewsstateContext.Provider>
  );
};

解决方法

好的,问题是返回了newsReducer中的默认操作,它应该只返回状态对象。

export const newsReducer = (state: NewsStateContextType,action: Action) => {
  switch (action.type) {
    case SET_NEWS:
      return action.payload;
    case ADD_NEWS:
      return { ...state,results: [...state.results,action.payload] };
    default:
      return state;
  }
};