前言
本文章主要是讲述如何通过useNavigate携带参数并在对应组件进行接收。
提示:以下是本篇文章正文内容,下面案例可供参考
一、如何携带search,params,state参数
import React, { memo } from 'react'import { useNavigate } from 'react-router-dom'const Home = memo(() => {const navigate=useNavigate() constgoDetail = () => {navigate('/Detail?name=tom&age=18')}const goAbout = () => {navigate('/About/jack')}const goshop = () => {navigate('/Detail/Shop', { state: {name:'tom',age:"20"} })}return ()})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:},{path: '/Detail',element: ,children: [{path: 'Shop',element:}]},{path: '/About/:name',element:},{path: '/',element:}])return routes})export default DefineRoutes
三,在App导入应用
import React, { memo } from 'react'import DefineRoutes from './router'const App = memo(() => {return ()})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 (About)})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 (Detail我是Detail的子组件
)})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 (Shop)})export default Shop
总结
不同的路由传参一定要注意,是否要在注册路由的时候接收,一定要使用对应的hook接收对应的参数。