日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

React路由組件三種傳參方式分析講解_React

作者:是張魚小丸子鴨 ? 更新時(shí)間: 2022-10-10 編程語言

路由組件和組件的區(qū)別

路由組件時(shí)被Router組件使用的組件,this.props里面有三個(gè)參數(shù),分別是history、match、location

可以接收到路由跳轉(zhuǎn)傳參,也可以進(jìn)行編程式導(dǎo)航跳轉(zhuǎn)

普通組件只有父傳子的props值

Swith內(nèi)置組件使用

作用:當(dāng)匹配一個(gè)路由組件時(shí),其他組件不會(huì)被使用,可以加入404頁面,給用戶進(jìn)行友好提示,提升用戶體驗(yàn)

react 路由傳參

方式一:url的query方式傳參,在App組件中

//傳值
<Link to='/home?name=張三&age=18'>主頁面</Link>
//接收
<Route path='/home' component={home}></Route>

如果我們要打印我們接收到的值,有兩種方式

第一種,在home組件中,創(chuàng)建一個(gè)生命周期,然后進(jìn)行普通的切割、添加、打印即可

    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>

注意:傳入的參數(shù)跟值得長度必須一致,否則會(huì)報(bào)錯(cuò)

打印:

    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>

打印:

componentDidMount(){
        console.log(this.props.location.user);
    }

編程式導(dǎo)航

我們定義一個(gè)按鈕,在按鈕中給他一個(gè)點(diǎn)擊事件,在事件函數(shù)中我們進(jìn)行路由得跳轉(zhuǎn)

home組件

export default class home extends Component {
    onchange=()=>{
        this.props.history.push('/home/?name=張三&age=19')
      }
  render() {
    return (
      <div>
        <button onClick={()=>{this.onchange()}}>點(diǎn)擊跳轉(zhuǎn)到home頁</button>
      </div>
    )
  }
}

在home 組件中,this.props.history.push后面跟上邊三種傳參方式

app組件

<Link to='/home?name=張三&age=18'>主頁面</Link>

Redirect重定向

跟我們vue中的redirect使用方法相似,用來路由跳轉(zhuǎn)

<Redirect to='/'></Redirect>

原文鏈接:https://blog.csdn.net/qq_60976312/article/details/125555745

欄目分類
最近更新