浅谈react的路由介绍

127 阅读1分钟

react路由

  • 编程式导航
  1. params传参数(react-router-dom 5.0版本)
  //路由匹配
  
   <Router>  
      <Switch>
        <Route  path='/home/:id' component={Home}></Route>
      </Switch>
    </Router>
    
 //路由跳转
   <button onClick={()=>this.pushpath()}>跳转到home页面</button>
    pushpath=()=>{
    console.log(this.props,'props')
    this.props.history.push(`/home/${'lyy'}`)
  }
  
 // 路由接参数
 console.log(this.props.match.params,'propshome')
 
 注意的点:路由的path需要在路由path上面匹配对应的参数
  1. search传参数
 //路由匹配
 
  <Router>  
     <Switch>
       <Route path='/about' component={About}></Route>
     </Switch>
   </Router>
   
//路由跳转
   <button onClick={()=>this.goAbout()}>我是跳转按钮,跳转到about页面</button>
 goAbout(){
   this.props.history.push(`/about?id=${'test'}`)
 }
 
// 路由接参数
   let {search} = this.props.history.location
   let id =(qs.parse(search.slice(1)))

注意的点:路由的path需不需要在路由上额外配置, 跳转的时候添加上key=value,接受的时候需要使用qs 格式化

3.state传参

 //路由匹配
 
  <Router>  
     <Switch>
       <Route  path='/test' component={Test}></Route>
     </Switch>
   </Router>
   
//路由跳转
   <button onClick={()=>this.goAbout()}>我是跳转按钮,跳转到about页面</button>
 goAbout(){
   this.props.history.push({pathname:'/about',state:{id:'lyy'}})
 }
 
// 路由接参数
    console.log(this.props.location.state,'propshome')

注意的点:路由的path需不需要在路由上额外配置, 跳转的时候{pathname:'/about',state:{id:'lyy'}