第一種傳參方式,動態路由傳參
通過設置link的path屬性,進行路由的傳參,當點擊link標簽的時候,會在上方的url地址中顯示傳遞的整個url
1
|
< Link to = '/home?name=dx' >首頁</ Link > |
如果想真正獲取到傳遞過來的參數,需要在對應的子組件中
this.props.location.search 獲取字符串,再手動解析
因為傳參能夠被用戶看見,傳遞獲取比較麻煩,所以不推薦
第二種傳參方式,隱式路由傳參
1
2
3
4
5
6
|
<Link to={{ pathname: 'about' , state: { name: 'dx' } }}>關于</Link> |
所謂隱式路由傳參,就是傳參的信息不回暴露在url中,當點擊該link標簽,想要獲取到傳遞的參數,就在對應的路由組件中,通過this.props.location.state獲取即可
推薦使用,比較安全,獲取傳遞參數都比較方便
第三種傳參方式 組件間傳參
何時使用?
當一個路由組件需要接收來自父組件傳參的時候
改造route標簽通過component屬性激活組件的方式
正常情況下的route標簽在路由中的使用方式
1
2
|
//簡潔明了,但沒辦法接收來自父組件的傳參 <Route path= '/test' component={Test}></Route> |
改造之后
1
2
3
4
5
6
7
8
|
<Link to= '/test' >測試</Link> <Route path= '/test' render={(routeProps) => { //routeProps就是路由組件傳遞的參數 return ( //在原先路由組件參數的情況,擴展綁定父組件對子組件傳遞的參數 <Test {...routeProps} name= 'dx' age={18} /> ) }}></Route> |
當點擊link標簽時,通過在對應的test子組件中,this.props獲取來自父組件傳遞的參數和路由組件自帶的參數
強烈推薦,傳遞參數略微有些麻煩,接收參數十分方便,并且仍然可以接收路由組件自帶的參數,安全,不會被用戶看見
第四種傳參方式 withRouter 高階組件給子組件綁定路由參數
withRouter 何時使用?
想要在某個子組件中獲取路由的參數,必須得使用路由中的route標簽的子組件才能被綁定上路由的參數。
為了解決不通過route標簽綁定的子組件獲取路由參數的問題,需要使用withRouter
一般用在返回首頁,返回上一級等按鈕上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import React from 'react' ; import BackHome from './backhome' ; export default class Test extends React.Component { render () { console.log( this .props) return ( <div> 這是測試的內容 //返回首頁的按鈕不是通過route標簽渲染的,所以該子組件的this.props中沒有路由參數 <BackHome>返回首頁</BackHome> </div> ) } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import React from 'react' ; //導入withRoute import {withRouter} from 'react-router-dom' ; class BackHome extends React.Component { goHome = () => { //必須在使用withRouter的情況下,該組件在this.props中才有路由參數和方法 //否則,會報錯 this .props.history.push({ pathname: '/home' , state: { name: 'dx' //同樣,可以通過state向home路由對應的組件傳遞參數 } }) } render () { return ( <button onClick={ this .goHome}> this .props.children</button> ) } } //導出的時候,用withRouter標簽將backHome組件以參數形式傳出 export default withRouter(BackHome) |
當你需要使用的時候,就很重要,所以還是比較推薦。
到此這篇關于淺談react路由傳參的幾種方式的文章就介紹到這了,更多相關react路由傳參內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/glorydx/article/details/104769742