react-router v6 轻使用

路由使用
App.tsx
import { BrowserRouter as Router } from "react-router-dom";
import { Suspense } from 'react'; // 配合动态加载的路由

const App = () => {

  return (
    <Router>
       <Suspense fallback={<div>222</div>}>
          {/* 自定义的路由文件 */}
         <RoutesComponents></RoutesComponents>
       </Suspense>
     </Router>
  )
}

export default App
routes.tsx
import {Routes, Route} from 'react-router-dom'
import React from 'react'

const Home = React.lazy(() => import('@/pages/home')) // 懒加载页面组件
const Note = React.lazy(() => import('@/pages/note'))

const RoutesComponents = () => {

  return (
    <Routes>
      <Route path="home/:id" element={<Home />} />
      <Route path="note" element={<Note />} /> 
      {/* 无匹配路由 放置在最后一个路由的位置 */}
      <Route path="*" element={<Home />} /> 
    </Routes>
  )
}

export default RoutesComponents
Home.tsx
import styles from './index.module.less'
import { useNavigate, useParams, useLocation, Link } from "react-router-dom";
import { Button } from 'antd';

const Home = () => {
  const navigate = useNavigate()
  const params = useParams() 
  // 通过params 可以获取到 路由(/home/:id)需要的参数信息   
  // /home/5 => params: { id: 5 } 
  console.log("🚀 ~ file: index.tsx ~ line 10 ~ Home ~ params", params) // { *: "home" }
  const location = useLocation()
  console.log("🚀 ~ file: index.tsx ~ line 14 ~ Home ~ location", location)
  // { 
  //   pathname: "/home",
  //   search: "?id=5", 路由问号传参的信息
  //   hash: "",
  //   state: {
  //     name: "amin" // 跳转过来的页面携带的路由信息 navigate('/note', { state: { name: 'zf' }})
  //   },
  //   key: "ns4b6nn3"
  // }

  const toHome = () => {
     navigate('/note', { state: { name: 'zf' }})
  }

  return (
    <div className={styles.homeContainer}>
      <div>
        <Button onClick={toHome}>to Note</Button>
        <Link to={'/note'}>to Note</Link>
      </div>
      <div>Home</div>
    </div>
  )
}

export default Home

嵌套路由使用及父路由传参给子路由

路由文件 routes.tsx
import {Routes, Route} from 'react-router-dom'
import React from 'react'

const Home = React.lazy(() => import('@/pages/home'))
const Note = React.lazy(() => import('@/pages/note'))
const Child = React.lazy(() => import('@/pages/home/components/child'))

const RoutesComponents = () => {

  return (
    <Routes>
      <Route path="home" element={<Home />}>
      	{/* 子路由嵌套在副路由里面, 路径为'', 默认为主路由 */}
      	{/* 路由开头不要加'/' */}
        <Route path="child" element={<Child />} />
        <Route path="" element={<Child />} />
      </Route>
      <Route path="note" element={<Note />} /> 
      
      {/* 无匹配路由 放置在最后一个路由的位置 */}
      <Route path="*" element={<Home />} /> 
    </Routes>
  )
}

export default RoutesComponents
父组件
import styles from './index.module.less'
import { useNavigate, useParams, useLocation, Link, Route, Routes } from "react-router-dom";
import { Button } from 'antd';
import React from 'react';
import { Outlet } from 'react-router-dom';

const Home = () => {
  const [count, setCount] = useState<number>(0)
  
  const toHome = () => {
    navigate('/note', { state: { name: 'zf' }})
  }

  return (
    <div className={styles.homeContainer}>
      <div>
        <Button onClick={toHome}>to Note</Button>
        <Link to={'/note'}>to Note</Link>
      </div>
      <div>Home</div>
	  {/* 父组件通过Outlet的context 向匹配到的子组件传递数据 */}
      <Outlet context={[count, setCount]}></Outlet>
    </div>

  )
}

export default Home
子组件
const Child = () => {
  // 子组件通过useOutletContext方法获取父组件传递进来的数据
  const [count, setCount] = useOutletContext<OutletType>();

  const onClick = () => {
    setCount((n: number) => n + 1)
  }
  
  return (
    <div>
      <div>Child</div>
      <div>
        <button onClick={onClick}>child deal count</button>
        <div>
          Child count {count}
        </div>
      </div>
    </div>
  )
}

export default Child
效果图

在这里插入图片描述

useSearchParams
import { Input } from "antd";
import React from "react";
import { useOutletContext, useSearchParams } from "react-router-dom";

type OutletType = [number, React.Dispatch<React.SetStateAction<number>>]

const Child = () => {
  const [count, setCount] = useOutletContext<OutletType>();
  const [searchParams, setSearchParams] = useSearchParams();
  console.log("🚀 ~ file: child.tsx ~ line 10 ~ Child ~ searchParams", searchParams)

  const handleSubmit = (event: any) => {
    event.preventDefault();
    // 修改input的内容会更新浏览器的参数信息
    // http://localhost:3000/home/child
    // http://localhost:3000/home/child?name=123
    setSearchParams({
      name: event.target.value
    })
  }

  return (
    <div>
      <div>Child</div>
      <div>
        <Input onChange={handleSubmit}></Input>
      </div>
    </div>
  )
}

export default Child

示例代码地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值