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

路由传值的三种方式(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

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

//备注:刷新也可以保留住参数
复制代码

为您推荐相关文章:

猜你喜欢

转载自juejin.im/post/7042849947451916296