【项目地址】
https://gitee.com/shangqiao1996/member-points-mgmt
一、声明式导航
(react-router@6 之前)
[match]
<NavLink to='/layout/First/zhangsan/18'>First</NavLink>
<Route path="/layout/First/:name/:age" component={First}></Route>;
this.props.match.params;
// {
// "name": "zhangsan",
// "age": "18"
// }
<NavLink
to={{
pathname: '/layout/Third',
state: { name: 'zhangsan', age: 18 }
}}
></NavLink>
this.props.location.state
// {
// "name": "zhangsan",
// "age": 18
// }
二、编程式导航
-
操作 history(react-router@6 之前)
[location.search] this.props.history.push('/layout/Fifth?name=zhangsan&age=18') this.props.location.search // ?name=zhangsan&age=18 [location.state] this.props.history.push('/layout/Sixth', { name: 'zhangsan', age: 18 }) this.props.location.state // { // "name": "zhangsan", // "age": 18 // } [match] this.props.history.push('/layout/Fourth/zhangsan/18') // 需要配置路由 <Route path='/layout/Fourth/:name/:age' component={Fourth}></Route> this.props.match.params // { // "name": "zhangsan", // "age": "18" // } [location.query] this.props.history.push({ pathname: '/layout/Seventh', query: { name: 'zhangsan', age: 18 } }) this.props.location.query // { // "name": "zhangsan", // "age": 18 // }
-
useNavigate()(react-router@6)【官方推荐】
import { useNavigate, useLocation, useParams } from "react-router"; import { useSearchParams } from "react-router-dom"; const location = useLocation(); const [searchParams] = useSearchParams(); const params = useParams(); // useNaviagte()('/points-get/promotion-points', { state: { name: 'shangqiao' } }) console.log("location", location.state); // navigate('/points-get/promotion-points?name=shangqiao&age=20'); console.log("searchParams", searchParams.getAll("name")); // navigate('/points-get/promotion-points/shangqiao'); console.log("params", params);