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

最佳答案

那这个呢:

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

关于reactjs - 有没有办法将泛型类型传递给react useReducer Hook 中使用的reducer?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56706065/

10-10 05:34