【问题标题】:How to wrap an HOC component twice如何将 HOC 组件包装两次
【发布时间】:2019-10-31 02:29:43
【问题描述】:

我在 reactjs 应用中有一个类组件,我希望它使用路由器和翻译。

interface CommonHeaderProps extends RouteComponentProps<any> {
}

class CommonHeader extends React.Component<CommonHeaderProps> {  

  render() {


    return (
      <div>

      </div>
    );
  }
}

const mapStateToProps = (state: RootState) => ({

})

const mapDispatchToProps = {};

export default withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(CommonHeader));

我希望这个组件是

withRouter()(CommonHeader)withTranslation()(CommonHeader)

但是这样做不起作用

export default withTranslation()(withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(CommonHeader)));

我试过了

const Component = connect(
  mapStateToProps,
  mapDispatchToProps
)(CommonHeader)

export default compose<CommonHeader>(
 withTranslation,
 withRouter,
)(Component)

但是当我尝试调用组件时出现以下错误:

JSX 元素类型“CommonHeader”没有任何构造或调用 签名

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    假设 withRouter()(CommonHeader)withTranslation()(CommonHeader) 都可以工作,看起来您仍然需要调用 compose 中的两个 HOC

    export default compose(
      withTranslation(), // note the `()`
      withRouter(),      // note the `()`
    )(Component)
    

    您也可以将connect 移动到compose

    export default compose(
      withTranslation(), 
      withRouter(), 
      connect(mapStateToProps, mapDispatchToProps,)
    )(CommonHeader)
    

    【讨论】:

    • 感谢您的回复,他们确实有效。 commonHeader 文件没有错误,但是当我从 App.tsx 调用它时,我仍然有相同的SX element type 'CommonHeader' does not have any construct or call signatures.
    • 想建立一个代码沙箱?很难提供指导,因为缺少很多上下文。
    • 你能去掉&lt;CommonHeader&gt;的类型转换,看看是否有效?
    • 将尝试制作一点,完成后 ping 你谢谢你的时间
    • 在我的情况下正确的选项是:导出默认 compose( withTranslation(), withRouter, connect(mapStateToProps, mapDispatchToProps,) )(CommonHeader)
    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2023-03-04
    • 2017-07-11
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多