【问题标题】:Is there a way to pass a generic type to the reducer used in react useReducer hook?有没有办法将泛型类型传递给 react useReducer 钩子中使用的减速器?
【发布时间】:2019-11-04 11:02:19
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-hooks typescript3.0


    【解决方案1】:

    这个呢:

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

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 2019-10-04
      • 2016-02-12
      相关资源
      最近更新 更多