路由传值的三种方式(v5.x)
1.params参数
//路由链接(携带参数):
<Link to='/demo/test/tom/18'}>详情</Link>
//或 <Link to={{ pathname:'/demo/test/tom/18' }}>详情</Link>
//注册路由(声明接收):
<Route path="/demo/test/:name/:age" component={Test}/>
//接收参数:
this.props.match.params
2.search参数
//路由链接(携带参数):
<Link to='/demo/test?name=tom&age=18'}>详情</Link>
//注册路由(无需声明,正常注册即可):
<Route path="/demo/test" component={Test}/>
//接收参数:
this.props.location.search
//备注:获取到的search是urlencoded编码字符串(例如: ?id=10&name=zhangsan),需要借助query-string解析参数成对象
3.state参数
//路由链接(携带参数):
<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
//注册路由(无需声明,正常注册即可):
<Route path="/demo/test" component={Test}/>
//接收参数:
this.props.location.state
//备注:刷新也可以保留住参数
路由传值的三种方式(v6.x)
1.params参数
//路由链接(携带参数):
<Link to={{ pathname:`/b/child1/${id}/${title}` }}>Child1</Link>
//或 <Link to={`/b/child1/${id}/${title}`}>Child1</Link>
//注册路由(声明接收):
<Route path="/b/child1/:id/:title" component={Test}/>
//接收参数:
import { useParams } from "react-router-dom";
const params = useParams();
//params参数 => {id: "01", title: "消息1"}
2.search参数
//路由链接(携带参数):
<Link className="nav" to={`/b/child2?age=20&name=zhangsan`}>Child2</Link>
//注册路由(无需声明,正常注册即可):
<Route path="/b/child2" component={Test}/>
//接收参数方法1:
import { useLocation } from "react-router-dom";
import qs from "query-string";
const { search } = useLocation();
//search参数 => {age: "20", name: "zhangsan"}
//接收参数方法2:
import { useSearchParams } from "react-router-dom";
const [searchParams, setSearchParams] = useSearchParams();
// console.log( searchParams.get("id")); // 12
3.state参数
//通过Link的state属性传递参数
<Link
className="nav"
to={`/b/child2`}
state={{ id: 999, name: "i love merlin" }}
>
Child2
</Link>
//注册路由(无需声明,正常注册即可):
<Route path="/b/child2" component={Test}/>
//接收参数:
import { useLocation } from "react-router-dom";
const { state } = useLocation();
//state参数 => {id: 999, name: "我是梅琳"}
//备注:刷新也可以保留住参数
为您推荐相关文章:
- 深度解析 React useRef Hook 的使用 ! https://blog.csdn.net/qq_42753705/article/details/121973014?spm=1001.2014.3001.5501
- 最简洁的 Mbox 6.x 基本使用步骤介绍(仅三步)!!!https://blog.csdn.net/qq_42753705/article/details/121909076?spm=1001.2014.3001.5501
- (干货) 全网最全 react-router-dom v6.0学习指南(新特性深入解读、持续更新…)!!!https://blog.csdn.net/qq_42753705/article/details/121871363?spm=1001.2014.3001.5501
- (原创)深入解读s React 中的useState Hook 修改了值,但是不重新渲染,不刷新的问提https://blog.csdn.net/qq_42753705/article/details/121837154?spm=1001.2014.3001.5501
- 在React中使用 react-router-dom 编程式路由导航的正确姿势【含V5.x、V6.x】https://blog.csdn.net/qq_42753705/article/details/122008800
- React中使用 react-router-dom 路由传参的三种方式详解【含V5.x、V6.x】!!!https://blog.csdn.net/qq_42753705/article/details/121998895