使用react-redux连接时如何流式输入道具

时间:2017-04-19 20:35:26

标签: reactjs redux react-redux flowtype

我想声明我的react-redux mapStateToProps函数返回了正确类型的属性,而不是省略任何属性。

如果我这样做,它会抱怨派遣道具。如果我没有$Exact,我认为它不会缺少或额外的道具。

我在想myComponent可以声明一个类型为Props的静态字段,所以我可以从那里读出类型,但这似乎是一个黑客,我需要为每个组件做。

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;
   ...
} 

1 个答案:

答案 0 :(得分:1)

我认为你不应该在道具上使用$Exact。在React中指定额外的道具并不是一个错误,很多库依赖于这种行为。如果您使用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中的对象类型已更改为 allow ,用于未在类型中指定额外字段的对象

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

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

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

相关问题