使用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-router
v6,它不支持类。因此,您应该在应用程序中创建一个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传给需要传值的组件
也可以改成函数式组件