gpt4 book ai didi

reactjs - 使用react-redux connect时如何流动类型 Prop

转载 作者:行者123 更新时间:2023-12-03 14:28:20 24 4
gpt4 key购买 nike

我想声明我的react-redux mapStateToProps 函数返回类型正确的属性并且不会遗漏任何属性。

如果我这样做,它会提示 props 中的调度。如果我做得不是$Exact,我认为它不会捕获丢失或额外的 Prop 。

我认为 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;
...
}

最佳答案

我认为你不应该将 $Exact 与 props 一起使用。在 React 中指定额外的 props 并不是错误,很多库都依赖于这种行为。如果您使用没有 $ExactProps 类型,它仍然会捕获丢失的 props ( "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." ),但不会提示传递了额外的 props (事实上, Flow 中对象类型的行为已更改为允许具有类型中未指定的额外字段的对象)

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

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

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

关于reactjs - 使用react-redux connect时如何流动类型 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com