react-类组件的路由传参-7种


react-router-dom版本:"react-router-dom": "5.2.1"

声明式导航

1. params传参---match

{/* params传参 */}
First



// 获取参数---match 
this.props.match.params 
// {
//    "name": "zhangsan",
//	  "age": "18"
// }
  1. 地址栏显示参数
  2. 需要配置动态路由

2. search传参---location

{/* search传参 */}
Second


    
// 获取参数---location
this.props.location.search
// ?name=zhangsan&age=18

地址栏显示参数

3. state传参---location

{/* state传参 */}

  Third




// 获取参数---location
this.props.location.state
// {
//     "name": "zhangsan",
//     "age": 18
// }

地址栏不显示参数

编程式导航

4. params传参---match

{/* params传参 */}

// 跳转方法
goToFourth = () => {
    this.props.history.push('/layout/Fourth/zhangsan/18')
}



// 获取参数---match
this.props.match.params
// {
//     "name": "zhangsan",
//     "age": "18"
// }
  1. 地址栏显示参数
  2. 需要配置动态路由

5. search传参---location

{/* search传参 */}

// 跳转方法
goToFifth = () => {
    this.props.history.push('/layout/Fifth?name=zhangsan&age=18')
}



// 获取参数---location
this.props.location.search
// ?name=zhangsan&age=18

地址栏显示参数

6. state传参---location

{/* state传参 */}

// 跳转方法
goToSixth = () => {
    this.props.history.push('/layout/Sixth', { name: 'zhangsan', age: 18 })
}



// 获取参数---location
this.props.location.state
// {
//     "name": "zhangsan",
//     "age": 18
// }

地址栏不显示参数

7. query传参---location

{/* query传参 */}

// 跳转方法
goToSeventh = () => {
  this.props.history.push({
    pathname: '/layout/Seventh',
    query: {
      name: 'zhangsan',
      age: 18
    }
  })
}



// 获取参数---location
this.props.location.query
// {
//     "name": "zhangsan",
//     "age": 18
// }
  1. 地址栏不显示参数
  2. 刷新获取不到数据

search参数转对象方法

// this.props.location.search
getSearch = (searchStr) => {
    const search = {}
    const arr = searchStr.slice(1).split('&')
    arr.forEach((e) => {
      const item = e.split('=')
      search[item[0]] = item[1]
    })
    return search
}