1. Realize the effect
Click menu message 1 to display
id
the details corresponding to 01;
click menu message 2 to displayid
the details corresponding to 02;
click menu message 3 to displayid
the details corresponding to 03;
2. Implementation method
params
Method 1. Pass parameters to the routing component
Detail
Pass parameters to the component id
andtitle
[Note: ``The template string is js
the stuff inside. When using this, add a curly bracket to the outer layer {}
]
【Note: Some pictures may be written in version 6.0, so the code below the picture shall prevail】
{
/* 第一步、向路由组件传递params参数——``模板字符串是js里的东西,使用这个(js表达式)时要在外层加个花括号{} */}
<Link to={
`/message/detail/${
msgObj.id}/${
msgObj.title}`}>{
msgObj.title}</Link>
{
/* 第二步、声明接收params参数 */}
<Route path="/message/detail/:id/:title" component={
Detail} />
receive params
parameters
In the Detail
component by this.props.match.params
receiving params
parameters
Method 2, pass search
parameters to the routing component
【Note: Some pictures may be written in version 6.0, so the code below the picture shall prevail】
{
/* 第一步、向路由组件传递search参数——``模板字符串是js里的东西,使用这个(js表达式)时要在外层加个花括号{} */}
<Link to={
`/message/detail/?id=${
msgObj.id}&title=${
msgObj.title}`}>{
msgObj.title}</Link>
{
/* 第二步、search参数无需声明接收,正常注册路由即可 */}
<Route path="/message/detail" component=<Detail} />
receive search
parameters
By this.props.location
getting it search
, and then you need to use qs
it to get the parameters~
qs
is anpm
package managed by a repository
qs.parse()
Parse the URL into the form of an objectqs.stringify()
URL
The form in which the object is serialized&
for splicing
state
Method 3. Pass parameters to the routing component
【Note: Some pictures may be written in version 6.0, so the code below the picture shall prevail】
{
/* 第一步、向路由组件传递state参数 */}
<Link to={
{
pathname:'/message/detail',state:{
id:msgObj.id,title:msgObj.title}}}>{
msgObj.title}</Link>
{
/* 第二步、state参数无需声明接收,正常注册路由即可 */}
<Route path="/message/detail" component={
Detail} />
receive state
parameters
In the Detail
component by this.props.location.state
receiving state
parameters
Summarize
向路由组件传递参数
1.params参数
路由链接(携带参数):<Link to='/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编码字符串,需要借助querystring(qs)解析
3.state参数
路由链接(携带参数):<Link to={
{
pathname:'/demo/test',state:{
name:'tom',age:18}}}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={
Test}/>
接收参数:this.props.location.state
备注:刷新也可以保留住参数
These are the study notes of the bilibili Shang Silicon Valley React learning video~