【问题标题】:how to type react-redux connect in flow?如何输入 react-redux connect in flow?
【发布时间】:2019-04-23 03:16:28
【问题描述】:

这就是我的mapStateToProps 的样子。

const mapStateToProps = (state): StateProps => {
    let status = false;
    if (state.productsPage.currentProduct) {
        if (state.productsPage.currentProduct.status === "ACTIVE") {
            status = true;
        }
    }
    return {
        showModal: state.productsPage.showModal,
        currentProduct: state.productsPage.currentProduct,
        isLoading: state.status.loading.PRODUCTS_EDIT,
        initialValues: {
            name: state.productsPage.currentProduct ? state.productsPage.currentProduct.name : "",
            status,
        },
    };
};

这是StateProps的形状

type StateProps = {
    showModal: boolean,
    currentProduct: Object,
    isLoading: boolean,
    initialValues: {
        name: string,
        status: boolean,
    }
}

这是我对连接的使用。

const connected = connect<React$StatelessFunctionalComponent<any>, StateProps>(mapStateToProps, mapDispatchToProps);

这会产生以下错误,我不知道这意味着什么或如何解决它。

[流程] 无法调用 connect,因为属性 currentProduct 是 索引器中的React.StatelessFunctionalComponent [1] 中缺少 类型参数ST 的属性键。 (参考文献:[1])

【问题讨论】:

    标签: javascript reactjs react-redux flowtype


    【解决方案1】:

    建议您将 Flow 至少升级到 0.89 以上,并使用Flow Typed's newest React Redux library definition

    然后,您可以使用PropsOwnProps 注释连接的组件

    import * as React from 'react'
    
    type OwnProps = {|
      passthrough: string,
      forMapStateToProps: string
    |}
    
    type Props = {|
      ...OwnProps,
      fromMapStateToProps: string,
      dispatch1: () => void
    |}
    
    const MyComponent = (props: Props) => (
      <div onClick={props.dispatch1}>
        {props.passthrough}
        {props.fromMapStateToProps}
      </div>
    )
    
    export default connect<Props, OwnProps, _, _, _, _>(
      mapStateToProps,
      mapDispatchToProps
    )(MyComponent)
    

    Here 是一份更详细的指南,其中包含更多用例。

    【讨论】:

      【解决方案2】:

      React$StatelessFunctionalComponent 是一个需要 prop 类型的泛型。除了&lt;any&gt;,您还需要该函数期望接收的道具——最重要的是,它期望接收由mapStateToProps 返回的StateProps(尽管它可能还期望其他人)。

      它可能会根据 react-redux 的版本而改变,但我看到一些文档表明 connect 的泛型是 mapStateToProps 的返回值,而不是 React 元素。 - Source

      您可能需要connect&lt;StateProps, DispatchPropsIfAny&gt; 而不是提供元素类型。

      【讨论】:

      • 不确定 any vs prop 类型,你可能是对的,很快就会尝试,但connect generics 中的第一个参数必须有一个可调用的签名,至少在 react 的版本中-redux flow typed 我正在使用。
      猜你喜欢
      • 2020-08-04
      • 2018-09-09
      • 2017-04-03
      • 2017-03-14
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      • 2020-07-05
      相关资源
      最近更新 更多