首页 > 解决方案 > 如何将 HOC 组件包装两次

问题描述

我在 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

解决方案


假设 withRouter()(CommonHeader)&withTranslation()(CommonHeader)都工作,看起来你仍然需要调用里面的两个 HOCcompose

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

也可以搬进connectcompose

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

推荐阅读