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不会暴露在导航栏
标签:title,ele,react,参数,组件,id,路由 From: https://www.cnblogs.com/wangdanmin/p/16658500.html