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

2022/4/2 6:21:53

本文主要是介绍react-类组件的路由传参-7种,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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

声明式导航

1. params传参---match

{/* params传参 */}
<NavLink to='/layout/First/zhangsan/18'>First</NavLink>

<Route path='/layout/First/:name/:age' component={First}></Route>

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

2. search传参---location

{/* search传参 */}
<NavLink to='/layout/Second?name=zhangsan&age=18'>Second</NavLink>

<Route path='/layout/Second' component={Second}></Route>
    
// 获取参数---location
this.props.location.search
// ?name=zhangsan&age=18

地址栏显示参数

3. state传参---location

{/* state传参 */}
<NavLink
  to={{
    pathname: '/layout/Third',
    state: { name: 'zhangsan', age: 18 }
  }}
>
  Third
</NavLink>

<Route path='/layout/Third' component={Third}></Route>

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

地址栏不显示参数

编程式导航

4. params传参---match

{/* params传参 */}
<button onClick={this.goToFourth}>buttonFourth</button>
// 跳转方法
goToFourth = () => {
    this.props.history.push('/layout/Fourth/zhangsan/18')
}

<Route path='/layout/Fourth/:name/:age' component={Fourth}></Route>

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

5. search传参---location

{/* search传参 */}
<button onClick={this.goToFifth}>buttonFifth</button>
// 跳转方法
goToFifth = () => {
    this.props.history.push('/layout/Fifth?name=zhangsan&age=18')
}

<Route path='/layout/Fifth' component={Fifth}></Route>

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

地址栏显示参数

6. state传参---location

{/* state传参 */}
<button onClick={this.goToSixth}>buttonSixth</button>
// 跳转方法
goToSixth = () => {
    this.props.history.push('/layout/Sixth', { name: 'zhangsan', age: 18 })
}

<Route path='/layout/Sixth' component={Sixth}></Route>

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

地址栏不显示参数

7. query传参---location

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

<Route path='/layout/Seventh' component={Seventh}></Route>

// 获取参数---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
}


这篇关于react-类组件的路由传参-7种的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程