javascript - 如何将泛型类型传递给 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。
解决方案
这将起作用:
const [state, dispatch] = useReducer<User>(returnAnyListReducer, initialState)
推荐阅读
- ruby - 从 Ruby 列表中删除/删除备用号码
- c# - 从门户下载代码并在本地测试后,Bot 框架代码不起作用
- vba - 使用 VBA 从选择中选择重复的最大数
- python - 如何在 Python 中高效地计算矩阵乘积的稀疏值?
- selenium - 如何将 10 个带有参数值的文件注入到 selenium 测试中并按顺序执行
- flutter - 方向生成器给出错误的方向
- .net - Xamarin,使用 .net Standard 2.0 和 Dependecy Services 创建 NuGet 包
- code-generation - 如何使用编写的 Xtend Generator 代码在 Xtext 中生成?
- azureservicebus - Azure 服务总线和 CAP 定理
- android - 如何在张量流上检测图像对象?