React路由传参的方法,以及5.x和6的区别

ReactRouter5

1、Params 方式

特点:参数只能是字符串,直接显示在地址栏上,Route中需要提前占位,刷新页面后参数不丢失。
第一步: 使用Link导航或NavLink导航

<Link to={`/home/message/detail/${item.id}}/${item.title}}`}>{item.title}</Link>

第二步: 在路由规则 Route 的 path 中定义参数名称

<Route path="/home/message/detail/:id/:title" component={Detail}></Route>

第三步: 在路由组件中,我们通过props来获取参数,props中包含history,location,match

const { id, title } = this.props.match.params

2、Search 方式

特点:和Vue中的query方式比较类似,Route中不需要提前占位。
第一步: 使用Link或NavLink导航

<Link to={`/home/message/detail/?id=${item.id}&title=${item.title}`}>{item.title}</Link>

第二步: 在Route定义规则

<Route path="/home/message/detail" component={Detail}></Route>

第三步: 在路由组件中,通过props来获取参数

let msg = new URLSearchParams(this.props.location.search.slice(1))
This is detail id:{msg.get('id')}---title:{msg.get('title')}

3、State 方式

特点:参数可以是对象,不显示在地址栏上,刷新后参数不丢失
第一步: 使用Link或NavLink导航,传递state对象

<Link to={{ pathname: '/home/message/detail', state: { id: item.id, title: item.title } }}>{item.title}</Link>

第二步: 在Route定义规则

<Route path="/home/message/detail" component={Detail}></Route>

第三步: 在路由组件中获取参数

const { id, title } = this.props.location.state || {};

最后5.x版本中需要注意的是:当我们在5.x版本中使用函数式组件时,通过路由来传递参数,我们需要使用withRouterAPI来渲染一般组件,使得组件具有history,location,match属性,这样我们才能正常的进行路由传参

ReactRouter6

与5.x版本主要的区别:

  1. 内置组件的变化:移除Switch,Redirect,新增Routes,Navigate
  2. 语法的变化:component={About} 变为 element={< About />}
  3. 新增了多个hook函数:useParams,useNavigate,useMatch,useRoutes等
  4. 官方明确推荐使用函数式组件

路由传参

主要的变化是在路由组件当中:
1、使用useParams来获取params参数

const { id, context } = useParams();

2、使用useSearchParams来获取search参数,useLocaiton也可以

const [search, setSearch] = useSearchParams();
This is news page---id:{search.get('id')}---context:{search.get('context')}

3、使用useLocation来获取state参数

const { id, context } = useLocation().state;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩浩不睡觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值