我正在尝试使用此article来实现React自定义钩子来进行数据提取。 这个自定义的钩子看起来像这样
type Action<T> =
| { type: "FETCH_INIT" }
| { payload: T; type: "FETCH_SUCCESS" }
| { error: string; type: "FETCH_FAILURE" };
interface IState<T> {
data: T;
error: string;
isLoading: boolean;
}
export const useFetch = <T>(initialUrl: string, initialData: T) => {
const initialState = {
data: initialData,
error: "",
isLoading: false,
};
const [state, dispatch] = useReducer<Reducer<IState<T>, Action<T>>>(dataFetchReducer, initialState);
...
};
问题是当我尝试键入dataFetchReducer
函数时。我不确定如何将通用类型从useFetch
传递到dataFetchReducer
。
这是dataFetchReducer
当前的样子。
const dataFetchReducer = <T>(state: IState<T>, action: Action<T>): IState<T> => {...};
我可能想得太多了,React实际上将泛型类型从useReducer
传递到dataFetchReducer
,但我不确定,我什至不知道如何测试这种行为。
答案 0 :(得分:0)
那呢:
export const reducer: <
TS extends IEntityState<IEntity>,
T extends IEntity
>(initialEntity: T) => React.Reducer<TS, Actions> = (initialEntity) => {
return (state, action) => {
switch(action.type) {
case ActionTypes.GET_ALL:
return {
...state,
entites: action.entites,
}
// ...
}
}
}
然后:
const [state, dispatch] = useReducer<React.Reducer<IStudentState, Actions>>
(reducer<IStudentState, IStudent>(initialStudent), initialState);