【问题标题】:react-router-dom v6 TypeScript withRouter for class components [duplicate]react-router-dom v6 TypeScript withRouter用于类组件[重复]
【发布时间】:2022-01-07 04:40:39
【问题描述】:

我正在尝试在我的 TypeScript React 应用中将 react-router-dom 更新为 v6

offical react-router-dom documentation 中只是声明:

随着升级到 v5.1,您应该用钩子替换 withRouter 的任何用法。

它完全忽略了类组件

我在网上搜索了很久,但找到的都是文章

  • 谈论 JavaScript 而不是 TypeScript,或
  • 谈谈功能组件,或
  • 参考react-router-domv5(或更低版本),因为他们谈论的是withRouter

在不需要将所有类组件重构为函数组件的 TypeScripp React 应用程序中,是否有一个有据可查的方法将 react-router-dom 升级到 v6?

【问题讨论】:

  • 你是对的,RRDv6 不再导出withRouter HOC。您可以将组件转换为函数组件,也可以使用 v6 挂钩创建自定义 withRouter HOC,并将“路由道具”注入装饰组件。

标签: reactjs typescript react-router-dom


【解决方案1】:

可能没有很好的文档记录,但this thread on GitHub 可能会为您提供正确的方向来完成这项工作。用户 mjackson 建议将您的类组件包装在一个 HOC 中,这样您就可以将 withRouter 挂钩和您的类组件连接在一起。

// in hocs.js
function withNavigation(Component) {
  return props => <Component {...props} navigate={useNavigate()} />;
}

function withParams(Component) {
  return props => <Component {...props} params={useParams()} />;
}

// in BlogPost.js
class BlogPost extends React.Component {
  render() {
    let { id } = this.props.params;
    // ...
  }
}

export default withParams(BlogPost);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2022-06-24
    • 2023-01-17
    • 2023-01-22
    • 2022-06-17
    • 2022-08-18
    相关资源
    最近更新 更多