【发布时间】:2021-03-18 13:07:38
【问题描述】:
我有以下减速器代码:
import { IState } from "./initialState";
import { TAction } from "./actions";
import * as types from './types';
const reducer = (state: IState, action: TAction): IState => {
const { type, payload } = action;
switch (type) {
case types.API_REQUEST:
return {
...state,
loading: true
};
case types.API_SUCCESS:
return {
...state,
loading: false,
data: payload
};
case types.API_ERROR:
return {
...state,
error: payload
};
default:
return state;
}
};
export default reducer;
在组件中的使用:
import * as React from "react";
import { useReducer } from "react";
import Context from './newsContext';
import reducer from "./store/reducer";
import initialState from "./store/initialState";
function News(): JSX.Element {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Context.Provider value={{ state, dispatch }}>
<h1>Hello World</h1>
</Context.Provider>);
}
上下文:
import initialState, { IState } from "./store/initialState";
import { TAction } from "./store/actions";
import { createContext, Dispatch } from "react";
interface IContextProps {
state: IState,
dispatch: Dispatch<TAction>;
}
const Context = createContext<IContextProps>({
dispatch: () => {
// Dispatch initial value
},
state: initialState
});
export default Context;
我的编译器显示 ts 错误:
TypeScript error in reactor-ts/src/news/News.tsx(7,42):
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: IState, action: TAction) => IState' is not assignable to parameter of type 'ReducerWithoutAction<any>'.
Overload 2 of 5, '(reducer: Reducer<any, any>, initialState: any, initializer?: undefined): [any, Dispatch<any>]', gave the following error.
Argument of type '(state: IState, action: TAction) => IState' is not assignable to parameter of type 'Reducer<any, any>'.
Types of parameters 'action' and 'action' are incompatible.
Type 'any' is not assignable to type 'never'.
The intersection 'TAction' was reduced to 'never' because property 'type' has conflicting types in some constituents. TS2769
知道我缺少什么 - 为什么编译器会失败?
【问题讨论】:
-
不要添加
IState,而是尝试为状态参数提供默认值。const reducer = (state = initialState, action: TAction) => {。看看这是否解决了问题 -
@Dilshan 谢谢,但没有:(
-
添加了完整代码的 git
标签: reactjs typescript react-typescript