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"
// }
- 地址栏显示参数
- 需要配置动态路由
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"
// }
- 地址栏显示参数
- 需要配置动态路由
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
// }
- 地址栏不显示参数
- 刷新获取不到数据
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
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现