使用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傳給需要傳值的組件
也可以改成函數式組件
