如何使用useNavigate 进行路由的跳转以及传参,并且获取参数。


前言

本文章主要是讲述如何通过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>About</div>
  )
})

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>Shop</div>
  )
})

export default Shop

总结

不同的路由传参一定要注意,是否要在注册路由的时候接收,一定要使用对应的hook接收对应的参数。