我在使用上下文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>
);
};
答案 0 :(得分:0)
好的,问题是返回了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;
}
};