react向路由组件传递参数数据的3种方式

1、params传递参数

步骤:

(1)路由链接(携带参数)

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

(2)注册路由(声明接收):

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

(3)接收参数:

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

2、search传递参数

步骤:

(1)路由链接(携带参数):

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

(2)注册路由(无需声明,正常注册即可):

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

(3)接收参数:

import qs from 'qs' /*react自带的库,18的引入方式*/
import qs from 'querystring' /*react自带的库,17的引入方式*/
const {search} = this.props.location
const {id,title} = qs.parse(search.slice(1)); /*转为对象形式*/

(4)其他: 获取到的search是urlencode编码字符串(id=1&name='test'),需要借助react自动下载的包querystring解析

3、传递参数

步骤:

(1)路由链接(携带参数,向路由组件传递state参数,{}表示写js,{{}}表示写对象,这里的to要是一个对象):

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

(2)注册路由(无需声明,正常注册即可):

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

(3)接收参数:

const {id,title} = this.props.location.state || {};
let item = list.find(ele=>ele.id === Number(id))|| {};

(4)其他:刷新也可以保留参数

4、总结

三种传递参数区别:params、search会把参数暴露在导航栏、state不会暴露在导航栏

posted @   小啊柒  阅读(655)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示