react路由传参方式

react/src/index.js里可以设置是HashRouter还是BrowserRouter模式

1. 设置为BrowserRouter

那么它显示的路由地址是这样:

 而且这么设置的好处是路由使用state传参时,刷新浏览器,而参数不会刷新,可以再次获取this.props.location.state的参数

2. 如果使用设置为HashRouter

那么 显示的路由地址是这样

但是设置为这模式,刷新浏览器后state传的参数就变为undefined了,也就是说刷新了就获取不了state传的参数了

 

 

接下来说下react路由传参的四种方式

1. 利用动态路由来实现params传参

设置路由:

 传参:

 

到Text.js接受参数

this.props.match.params // 结果 {id: "22", name: "jackal"}

除了params传参,其他一律为这种写法

 

 

2.通过search来传参,参数会显示在浏览器上面,并且刷新浏览器后还会在

传参:

this.props.history.push( {pathname: '/text', search:'name=hehe&age=22' } )
接受参数:
this.props.location.search // 结果 search: "?name=hehe&age=22"
 

 

 3.通过state来传参,但是参数不会显示在浏览器地址上面

传参:

this.props.history.push( {pathname: '/text', state:{name:'hehe',age:22} } )
接受参数:
this.props.location.state // 结果 state: {name: "hehe", age: 22}
 
注意:此传参方式在BrowserRouter模式下刷新浏览器参数还在,在HashRouter模式下刷新浏览器参数就不存在了,这时可以用本地存储来把参数存储再用
 
 
 
4.通过query来传参,但是参数不会显示在浏览器地址上面,刷新后参数消失

 传参:

history.push( {pathname: '/text', query:{name:'hehe',age:22}, state:{name:'hehe2',age:22} } )

 接受参数:

 

this.props.location.query / / 结果  query: {name: "hehe", age: 22}

 



 

posted @ 2020-07-18 17:55  强者之途  阅读(362)  评论(0)    收藏  举报
/* 看板娘 */