其他分享
首页 > 其他分享> > react-类组件的路由传参-7种

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
}

标签:传参,---,search,react,location,props,zhangsan,路由
来源: https://www.cnblogs.com/chichi13/p/16089684.html