关于类组件无法获得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传给需要传值的组件

也可以改成函数式组件

posted @ 2021-12-21 11:09  柠檬派的奇幻漂流  阅读(756)  评论(0)    收藏  举报