关于类组件无法获得params路由传值的解决方法


使用react-router-dom时,发现类组件无法使用useParams()获得传入的路径传值,搜罗了以下解决方法

1.使用的v5:您可以使用withRouter在组件中获取param

  

import { withRouter } from "path/to/withRouter";

export default withRouter(需要监听的组件);

并使用this.props.match.params获取您的参数:

const params = this.props.match.params;

2.使用的v6:因为您使用的是react-routerv6,它不支持类。因此,您应该在应用程序中创建一个withRouter

withRouter.jsx:

export function withRouter( Child ) {
  return ( props ) => {
    const params = useParams();
    const navigate = useNavigate();
    return <Child { ...props } params ={ params } />;
  }
}

您需要在类组件的constructor中添加super(props)

总结:在外面包裹一层withRouter获得params,通过props传给需要传值的组件

也可以改成函数式组件


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM