简体   繁体   English

如何将 generics 类型传递给 React Hooks useReducer

[英]How to pass generics type to React Hooks useReducer

I'm using React Hooks useReducer with Typescript. Then I'd like to pass type to useReducer.我将 React Hooks useReducer 与 Typescript 一起使用。然后我想将类型传递给 useReducer。 How can I pass type to Reducer Function, generics type.如何将类型传递给 Reducer Function、generics 类型。

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

And, component which uses this reducer is like this below.而且,使用这个减速器的组件如下所示。

 const initialState = {
  list: [],
 }

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

I have no idea how to pass type, for example User interface or AdminUser interface to useReducer.我不知道如何将类型传递给 useReducer,例如User界面或AdminUser界面。

This will work:这将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM