有没有办法将泛型类型传递给react useReducer挂钩中使用的reducer?

时间:2019-06-21 15:10:09

标签: reactjs react-hooks typescript3.0

我正在尝试使用此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,但我不确定,我什至不知道如何测试这种行为。

1 个答案:

答案 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);