我正在尝试在我的TypeScript React应用程序中将react-router-dom
更新为v6。
在官方的react路由器dom文档中简单地说明:
在升级到v5.1的同时,您应该用钩子替换
withRouter
的任何用法。
它完全忽略类组件!
我在网上搜索了很长时间,但我找到的所有文章都是
- 谈论JavaScript而不是TypeScript,或者
- 谈论功能组件,或者
- 请参阅
react-router-dom
的v5(或更低版本(,因为他们谈到了withRouter
在TypeScripp react应用程序中,是否有一种有充分记录的方法可以将react路由器dom升级到v6,而无需将所有类组件重构为功能组件
也许没有很好的文档,但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);