react-router 路由传参

路由传递参数

我们知道前端想后台传递参数有两种方式:
一种是直接将参数放在地址栏里面传递,这里又有两种方式:
/home?name=fly&age=18和/home/fly/18
另外一种方式是将参数放在body里面传递
这里针对第一种的两个传递方式:
App.js

export default class App extends Component {
     
    render() {
     
      return (
        <Router>
          <Link to="/home/a">Home</Link>---
          <Link to="/about?name=fly&age=18">About</Link>
          <br />
          <Route exact path='/home' component={
     Home}></Route>
          <Route path='/about' component={
     About}></Route>
        </Router>
      )
    }
  }

那么在about组件里面接收参数的形式;
about.js:

import React, {
      Component } from 'react'

export default class index extends Component {
     
  componentDidMount(){
     
    console.log(this.props)
  }
  render() {
     
    return (
      <div>
        this is about page
      </div>
    )
  }
}

react-router 路由传参_第1张图片
可以这样拿到参数:
abut.js:


export default class index extends Component {
     
  componentDidMount(){
     
    // console.log(this.props)
    console.log(this.props.location.search.substring(1).split('&'))
  }
  render() {
     
    return (
      <div>
        this is about page
      </div>
    )
  }
}

react-router 路由传参_第2张图片
about.js:

export default class index extends Component {
     
  componentDidMount(){
     
    // console.log(this.props)
    // console.log(this.props.location.search.substring(1).split('&'))
    let params =new URLSearchParams(this.props.location.search)
    console.log(params.get('name'))
    console.log(params.get('age'))
  }
  render() {
     
    return (
      <div>
        this is about page
      </div>
    )
  }
}

react-router 路由传参_第3张图片

另外一种传递方式:
App.js:

import React, {
      Component } from 'react'
// import { HashRouter,Link,Route } from 'react-router-dom'
import {
      BrowserRouter as Router,Link,Route } from 'react-router-dom'
import {
      Home,About } from './components'

  export default class App extends Component {
     
    render() {
     
      return (
        <Router>
          <Link to="/home/a">Home</Link>---
          <Link to="/about/fly/18">About</Link>
          <br />
          <Route exact path='/home' component={
     Home}></Route>
          <Route path='/about/:name/:age' component={
     About}></Route>
        </Router>
      )
    }
  }

记住用这个方式传递的时候:
/fly/18,是需要在后台的端口占位的,要不然是获取不到参数的;
react-router 路由传参_第4张图片
那么这个方式获取参数的方式还容易一些;

import React, {
      Component } from 'react'

export default class index extends Component {
     
  componentDidMount(){
     
    // console.log(this.props)
    // console.log(this.props.location.search.substring(1).split('&'))
    // let params =new URLSearchParams(this.props.location.search)
    // console.log(params.get('name'))
    // console.log(params.get('age'))
    console.log(this.props.match.params.name)
    console.log(this.props.match.params.age)
  }
  render() {
     
    return (
      <div>
        this is about page
      </div>
    )
  }
}

react-router 路由传参_第5张图片

你可能感兴趣的:(react,react)