4

React中使用 react-router-dom 路由传参的三种方式详解【含V5.x、V6.x】!!!

 2 years ago
source link: https://segmentfault.com/a/1190000041136562
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

路由传值的三种方式(v5.x)

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
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解析参数成对象
state参数
//路由链接(携带参数):
<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>

//注册路由(无需声明,正常注册即可):
 <Route path="/demo/test" component={Test}/>
    
//接收参数:
this.props.location.state

//备注:刷新也可以保留住参数

路由传值的三种方式(v6.x)

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"}
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

//备注:获取到的search是urlencoded编码字符串(例如: ?age=20&name=zhangsan),需要借助query-string解析参数成对象
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: "我是梅琳"}

//备注:刷新也可以保留住参数

兄弟姐妹们,点波关注吧,一起分享有趣的技术!

掘金https://juejin.cn/user/303430... 全部原创好文

CSDNhttps://blog.csdn.net/qq_4275... 全部原创好文

简书https://www.jianshu.com/u/460... 全部原创好文

segmentfault 思否https://segmentfault.com/u/ja... 全部原创好文

博客园https://www.cnblogs.com/Jason... 全部原创好文


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK