React路由組件三種傳參方式分析講解
路由組件和組件的區(qū)別
路由組件時被Router組件使用的組件,this.props里面有三個參數,分別是history、match、location
可以接收到路由跳轉傳參,也可以進行編程式導航跳轉
普通組件只有父傳子的props值
Swith內置組件使用
作用:當匹配一個路由組件時,其他組件不會被使用,可以加入404頁面,給用戶進行友好提示,提升用戶體驗
react 路由傳參
方式一:url的query方式傳參,在App組件中
//傳值
<Link to='/home?name=張三&age=18'>主頁面</Link>
//接收
<Route path='/home' component={home}></Route>如果我們要打印我們接收到的值,有兩種方式
第一種,在home組件中,創(chuàng)建一個生命周期,然后進行普通的切割、添加、打印即可
componentDidMount(){
console.log(this.props.history.location.search);
let a=this.props.history.location.search.slice(1)
let b=a.split('&')
console.log(b);
let obj={}
b.forEach((item)=>{
item.split('=')
obj[item.split('=')[0]]=item.split('=')[1]
})
console.log(obj);
}第二種:使用querystring,在使用之前,需要下載引入
下載:npm i querystring -D
componentDidMount(){
let a=this.props.history.location.search.slice(1)
console.log(querystring.parse(a));
}在頁面使用:querystring.parse(url形式攜帶的字符串)
方式二:url的params傳參
//傳值
<Link to='/login/zhangsan/18'>登錄</Link>
//接收
<Route path='/login/:name/:age' component={login}></Route>注意:傳入的參數跟值得長度必須一致,否則會報錯
打?。?/p>
componentDidMount(){
// console.log(this.props);
console.log(this.props.match.params);
}方式三:
//傳值
<Link to={{pathname:'/zhuce',user:{name:'張三',age:19}}}>注冊頁面</Link>
//接收
<Route path='/zhuce' component={zhuce}></Route>打?。?/p>
componentDidMount(){
console.log(this.props.location.user);
}編程式導航
我們定義一個按鈕,在按鈕中給他一個點擊事件,在事件函數中我們進行路由得跳轉
home組件
export default class home extends Component {
onchange=()=>{
this.props.history.push('/home/?name=張三&age=19')
}
render() {
return (
<div>
<button onClick={()=>{this.onchange()}}>點擊跳轉到home頁</button>
</div>
)
}
}在home 組件中,this.props.history.push后面跟上邊三種傳參方式
app組件
<Link to='/home?name=張三&age=18'>主頁面</Link>
Redirect重定向
跟我們vue中的redirect使用方法相似,用來路由跳轉
<Redirect to='/'></Redirect>
到此這篇關于React路由組件三種傳參方式分析講解的文章就介紹到這了,更多相關React路由組件傳參內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react組件memo useMemo useCallback使用區(qū)別示例
這篇文章主要為大家介紹了react組件memo useMemo useCallback使用區(qū)別的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07

