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