【问题标题】:How should I configure Flow type checking for functions that are passed as props in a React / Redux app?我应该如何为在 React / Redux 应用程序中作为 props 传递的函数配置流类型检查?
【发布时间】:2018-03-11 00:05:59
【问题描述】:

我在整个应用程序中将我的 Redux 动作创建者作为道具传递。到目前为止,我一直在使用通用的 Function 类型,但我宁愿进行适当的类型检查,以便知道我正在使用正确的参数和类型调用我的动作创建者。

我尝试在我的 Props 类型中使用存在运算符 (*),但 Flow 似乎无法推断函数签名(它只返回 any。)

我想出的最佳解决方案是在我的所有组件中从我的减速器中导入动作创建器,并使用typeof 来设置函数类型。例如:

import { actionCreator } from 'redux/modules/reducer'

type ComponentProps = {
    actionCreator: typeof actionCreator,
}

我很高兴在我的主容器中这样做一次,但是如果我必须在我的所有子组件中递归地添加所有这些类型定义,这将变得非常重复。

我想知道为什么以下内容在我的子组件中不起作用:

type ComponentProps = {
    actionCreator: *,
}

我希望函数类型通过我的 props 自动向下流动,但似乎 React 组件之间存在边界。

【问题讨论】:

    标签: javascript reactjs types redux flowtype


    【解决方案1】:

    你可以试试这个:

    type Action = (dispatch: Dispatch, ownProps?: { [prop: string]: any}) => void;
    type ActionCreator = (param1: string, param2: number, ...) => Action;
    

    注意,使用这种 Dispatch 类型需要包含 redux flow 类型的备忘单。

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多