繁体   English   中英

打字稿使用 actionType 作为子组件中的属性来响应 redux 和 redux-thunk

[英]typescript react redux and redux-thunk using actionType as property in child component

我在父组件Tasks 中有两个组件 Tasks 和 Task 的示例我已经连接了商店

type Props = ConnectedProps<typeof connector>
const mapDispatchToProps = { updateTask };
const connector = connect(mapStateToProps, mapDispatchToProps);
export default connector(Tasks)

然后在子任务中我想使用 updateTask 因为我不想将每个任务连接到 redux

任务看起来像

type Props = {
  updateTask: typeof updateTask
}

但该代码导致

类型 '(taskId: string, updatedTask: Partial) => void' 不能分配给类型 '(taskId: string, updatedTask: Partial) => ThunkAction'。 “void”类型不能分配给“ThunkAction”类型。

当然,因为它不通过 redux connect

所以我的问题是使用“react-redux”库中的InferThunkActionCreatorType是否安全?

type Props = {
  updateTask: InferThunkActionCreatorType<typeof updateTaskAndPropagate>
}

定义是

export type InferThunkActionCreatorType<TActionCreator extends (...args: any[]) => any> =
    TActionCreator extends (...args: infer TParams) => (...args: any[]) => infer TReturn
        ? (...args: TParams) => TReturn
        : TActionCreator;

这正是我需要的相同函数参数,但返回类型为 void

是的,这是您用例的完美类型。 它是Connect类型(连接函数的签名)中使用的内容,因此它准确地模仿了您正在寻找的内容。

所以你会做

type Props = {
  updateTask: InferThunkActionCreatorType<typeof updateTask>
}

哦,以防万一你不知道:现在有一个ConnectedProps类型可以让你更轻松地输入connect文档

通常可能会派上用场:)

暂无
暂无

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

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