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

“No overload matches this call” error when setting up ContextApi & useReducer using Typescript

我在使用上下文 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>
  );
};

好的,所以问题是 return在 newsReducer 的默认操作中,它应该 return 只是状态对象。

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;
  }
};