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 @ 2022-09-05 16:02  小啊柒  阅读(694)  评论(0)    收藏  举报