reactjs - 如何将 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”没有任何构造或调用签名
解决方案
假设 withRouter()(CommonHeader)
&withTranslation()(CommonHeader)
都工作,看起来你仍然需要调用里面的两个 HOCcompose
export default compose(
withTranslation(), // note the `()`
withRouter(), // note the `()`
)(Component)
也可以搬进connect
去compose
export default compose(
withTranslation(),
withRouter(),
connect(mapStateToProps, mapDispatchToProps,)
)(CommonHeader)
推荐阅读
- flutter - Flutter - 文本小部件更新一次迭代太晚了
- flutter - 显示从 TimePicker 中选择的时间以在 Flutter App 中显示本地通知
- android - 尝试写入文件时如何解决 Flutter 错误:“OS 错误:不允许操作,errno = 1”?
- proc-sql - SQL:有没有办法在同一个 SELECT 语句中使用新的/用户定义的变量?
- android - 想知道继续以下 Rx 链的最佳方式是什么,我需要决定调用 flatmap 还是 switchmap?
- html - 为什么文本会超出 div 容器?
- visual-studio-code - 调试控制台出错时跳转到链接的快捷方式是什么?
- python - 将值插入目录路径的字符串中不起作用
- azure - 为什么我的应用无法与 azure 应用服务上的 websocket 通信?
- sql-server - 在 DBeaver (MAC) 上为 SQL Server 连接本地主机