【问题标题】:How to flow-type props when using react-redux connect使用 react-redux 连接时如何流动类型的道具
【发布时间】:2017-09-16 06:21:42
【问题描述】:

我想声明我的 react-redux mapStateToProps 函数正在返回正确类型的属性并且没有省略任何属性。

如果我这样做,它会抱怨在道具中调度。如果我不是$Exact,我认为它不会捕获丢失或额外的道具。

我在想 myComponent 可以声明一个类型为 Props 的静态字段,这样我就可以从那里读取类型,但这似乎是一种 hack,我需要为每个组件都这样做。

src/mycomponent/index.js:

import {connect} from 'react-redux'
import type {Props} from './myComponent';
import MyComponent from './myComponent'

function mapStateToProps(state: State): $Exact<Props> {
  return {
    myKey: state.myKey,
  };
}

export default connect(mapStateToProps)(MyComponent);

src/myComponent/myComponent.js

type Props = {
  myKey: string,
}

export default class MyComponent extends React.Component {
   props: Props;
   ...
} 

【问题讨论】:

    标签: reactjs redux react-redux flowtype


    【解决方案1】:

    我认为您不应该将$Exact 与道具一起使用。在 React 中指定额外的 props 并不是错误,很多库都依赖于这种行为。如果你使用Props 类型而不使用$Exact,它仍然会捕获丢失的道具("In JavaScript, accessing a property that doesn’t exist evaluates to undefined. This is a common source of errors in JavaScript programs, so Flow turns these into type errors."),但不会抱怨传递了额外的道具(实际上,Flow 中对象类型的行为已更改为 允许类型中未指定额外字段的对象)

    当然,这里理想的解决方案是让 Flow 允许扩展对象类型,例如:

    type Props = { /* ... */ }
    type ReduxProps = { ...Props, dispatch: /* ... */ }
    

    虽然这个功能没有落地,但我相信最好容忍额外的道具被传递。它也应该是相当安全的,因为 Flow 不会让你从未知的 props iirc 中读取。

    【讨论】:

    • 您可以将 proptypes 与 & 运算符结合使用。所以你可以有类似type Props = OwnProps &amp; ReduxProps &amp; ReduxDispatchers &amp; etc
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2019-02-07
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多