react路由动态传递参数
[react-router-dom@6的三种传参方式 - 掘金](https://juejin.cn/post/7104185670712688653)
react-router-dom@6的三种传参方式
1. 子路由携带形式
路由配置代码
function App() {
return (
<BrowserRouter>
<Routes>
<Route path={'/'} element={<Login/>} />
<Route path={'/home/:id'} element={<Home/>} />
</Routes>
</BrowserRouter>
)
}
复制代码
原页面代码
const navigate = useNavigate()
const goHome = () => {
navigate("/home/123")
}
复制代码
目标页面代码
const params = useParams()
const back = () => {
console.log(params.id) //打印结果为 123
}
复制代码
2. 问号(?)形式传参
这种形式不需要再配置路由代码
原页面代码
const navigate = useNavigate()
const goHome = () => {
navigate("/home?id=123")
}
复制代码
跳转页面代码
const [params] = useSearchParams()
const back = () => {
console.log(params.getAll('id')[0]) //打印结果为 123
}
复制代码
3.通过state传参
原页面代码
const navigate = useNavigate()
const goHome = () => {
navigate("/home",{state:{id:123}})
}
复制代码
目标页面代码
const location:any = useLocation()
const back = () => {
console.log(location.state.id) //打印结果为123
}
复制代码
使用ts时需要配置location的数据类型,上述中暂时配置为any
作者:三秋Sanqiu
链接:https://juejin.cn/post/7104185670712688653
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
[react-router-dom ^6.0.0 怎样动态跳转页面以及传递参数 - Regina_wisdom - 博客园](https://www.cnblogs.com/Regina-wisdom/p/15479240.html)
[(32条消息) 2021-07-27 React useHistory 更新为useNavigate如何传值_qq_42999450的博客-CSDN博客_usehistory传参](https://blog.csdn.net/qq_42999450/article/details/119138461)
[react-router-dom基本使用+3种传参方式 - smile_or - 博客园](https://www.cnblogs.com/sgs123/p/14077680.html)
react-router-dom基本使用+3种传参方式
//App.js
import {
BrowserRouter as Router,
Route,
Link,
} from "react-router-dom";
// 引入组件
import Home from "....";
import News from "...."
function App() {
return (
<Router>
<Link to="/">首页</Link>
<Link to="/news">新闻</Link>
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
</Router>
);
}
export defautl App;
如何传递参数(3种)
1、params传参(动态路由)
特点:刷新页面参数不消失,参数会在地址栏显示
- 路由配置
<Route path='/about/:id' component={About} />
- 跳转方式
//传递参数可以拆分为对象写法:{pathname:'/about/3'}
//html:
<Link to={'/about/3'}>点击跳转</Link>
//js:
this.props.history.push('/about/3')
- 获取值
this.props.match.params.id // 3
2、query传参
特点:刷新页面参数消失,参数不会在地址栏显示
- 路由配置
<Route path='/about' component={About} />
- 跳转方式
//html:
<Link to={{pathname:'/about', query:{id:3}}}>点击跳转</Link>
//js:
this.props.history.push({pathname:'/about', query:{id:3}})
- 获取值
this.props.location.query.id // 3
3、state传参
特点:刷新页面参数不消失,参数不会在地址栏显示
- 路由配置
<Route path='/about' component={About} />
- 跳转方式
//html:
<Link to={{pathname:'/about', state:{id:3}}}>点击跳转</Link>
//js:
this.props.history.push({pathname:'/about', state:{id:3}})
- 获取值
this.props.location.state.id // 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?