首页 > 解决方案 > 如何将泛型类型传递给 React Hooks useReducer

问题描述

我正在使用带有 Typescript 的 React Hooks useReducer。然后我想将类型传递给 useReducer。如何将类型传递给 Reducer Function,泛型类型。

interface ActionTypes {
 FETCH,
}

interface TestPayload<T> {
 list: T[];
}

interface State<T> {
 list: T[];
}

interface Action<T> {
 type: ActionTypes;
 payload: TestPayload<T>;
}

export const returnAnyListReducer = <T>(
  state: State<T>, action: Action<T>
  ): State<T> => {
  const { type, payload } = action;
    switch (type) {
      case ActionTypes.FETCH: {
        return ({
          ...state,
          list: payload.list,
        });
      }
    }
  }

并且,使用该减速器的组件如下所示。

 const initialState = {
  list: [],
 }

 const [state, dispatch] = useReducer(returnAnyListReducer, initialState)

我不知道如何传递类型,例如User接口或AdminUser接口到 useReducer。

标签: javascriptreactjstypescriptreact-hooks

解决方案


这将起作用:

const [state, dispatch] = useReducer<User>(returnAnyListReducer, initialState)

推荐阅读