如何使用useNavigate 进行路由的跳转以及传参,并且获取参数。
admin 阅读: 2024-04-01
后台-插件-广告管理-内容页头部广告(手机) |
前言
本文章主要是讲述如何通过useNavigate携带参数并在对应组件进行接收。
提示:以下是本篇文章正文内容,下面案例可供参考
一、如何携带search,params,state参数
- import React, { memo } from 'react'
- import { useNavigate } from 'react-router-dom'
- const Home = memo(() => {
- const navigate=useNavigate()
- const goDetail = () => {
- navigate('/Detail?name=tom&age=18')
- }
- const goAbout = () => {
- navigate('/About/jack')
- }
- const goshop = () => {
- navigate('/Detail/Shop', { state: {name:'tom',age:"20"} })
- }
- return (
- <div>
- <button onClick={goDetail}>点我去Detail页面并且传递search参数button>
- <button onClick={goAbout}>点我去About页面并且传递params参数button>
- <button onClick={goshop}>点我去shop页面并且传递state参数button>
- div>
- )
- })
- export default Home
二、写对应的路由规则
- import { useRoutes,Navigate } from "react-router-dom";
- import Home from "../pages/Home";
- import Detail from "../pages/Detail";
- import About from "../pages/About";
- import Shop from "../pages/Shop";
- import React, { memo } from 'react'
- const DefineRoutes = memo(() => {
- const routes= useRoutes(
- [
- {
- path: '/Home',
- element:<Home>Home>
- },
- {
- path: '/Detail',
- element: <Detail>Detail>,
- children: [
- {
- path: 'Shop',
- element:<Shop>Shop>
- }
- ]
- },
- {
- path: '/About/:name',
- element:<About>About>
- },
- {
- path: '/',
- element:<Navigate to='/Home'>Navigate>
- }
- ]
- )
- return routes
- })
- export default DefineRoutes
三,在App导入应用
- import React, { memo } from 'react'
- import DefineRoutes from './router'
- const App = memo(() => {
- return (
- <div>
- <DefineRoutes>DefineRoutes>
- div>
- )
- })
- export default App
一定一定要在App组件外面包裹一层router,比如BrowerRouter
四,在不同的组件中获取不同的参数
获取Params参数使用useParams
- import React, { memo } from 'react'
- import { useParams } from 'react-router-dom'
- const About = memo(() => {
- console.log(useParams())
- return (
- <div>Aboutdiv>
- )
- })
- export default About
获取search参数使用useSearchParams
- import React, { memo } from 'react'
- import {Outlet, useSearchParams } from 'react-router-dom'
- const Detail = memo(() => {
- const [search,setsearch] = useSearchParams()
- console.log(search.get('name'))
- console.log(search.get('age'))
- return (
- <div>Detail
- <h1>我是Detail的子组件h1>
- <Outlet>Outlet>
- div>
- )
- })
- export default Detail
使用useLocation获取search参数
- import React, { memo } from 'react'
- import { useLocation } from 'react-router-dom'
- const Shop = memo(() => {
- const state = useLocation()
- console.log(state)
- return (
- <div>Shopdiv>
- )
- })
- export default Shop
总结
不同的路由传参一定要注意,是否要在注册路由的时候接收,一定要使用对应的hook接收对应的参数。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。
在线投稿:投稿 站长QQ:1888636
后台-插件-广告管理-内容页尾部广告(手机) |