当前位置: 首页 > news >正文

React-router路由配置及跳转

1、V6对比V5的修改内容

1、API: useNavigate 代替了useHistory
2、废弃了Route组件的exact属性。
3、组件 <Routes>代替了<Switch>
4、组件NavLink中移除了 activeStyle activeClassName 属性。

2、安装依赖react-router-dom

npm install react-router-dom -S

3、创建文件配置router.jsx

import { Route } from 'react-router-dom';
import Login from '@views/login/Index.jsx';
import Settings from '@views/settings/Index.jsx';// 定义路由配置数组
const routes = [{path: '/',component: Login,},{path: '/login',component: Login,},{path: '/settings',component: Settings,},
];// 将路由配置数组转换为Route组件(注意:Component属性是大写开头)
const renderRoutes = () => routes.map((route, index) => (<Routekey={index}path={route.path}Component={route.component}/>
));export default renderRoutes;

4、在APP.jsx文件中引入并使用

import renderRoutes from '@router/index.jsx';
import{HashRouter, Routes,Route,Router}from"react-router-dom";
function App() {return (<div><HashRouter><Routes>{renderRoutes()}</Routes></HashRouter></div>)
}export default App;

如果不单独配置router.jsx的话,也可以在APP.jsx中直接写

import Login from './views/login/Index.jsx';
import Settings from './views/settings/Index.jsx';
import{HashRouter, Routes,Route,Router}from"react-router-dom"
function App() {return (<div><HashRouter><Routes><Route path="/" Component={Login}></Route><Route path="/settings" Component={Settings}></Route></Routes></HashRouter></div>)
}export default App;

5、路由跳转

举例:在登录页面,点击

import { useNavigate } from "react-router-dom";
const Login = () => {const Navigate = useNavigate();const goSettings = () => {Navigate('/settings');};return (<div><button onClick={goSettings}>跳转到设置页面</button></div>)
};
export default Login;

注意

1、Route组件的常用属性有以下:
path:与URL匹配的路径
children:嵌套的路由配置
element/Component: 元素/组件
lazy:返回一个动态的组件引入。
2、Route中没有属性name

http://www.lryc.cn/news/406638.html

相关文章:

  • vue3【实战】可编辑的脱敏信息
  • S71200 - 笔记
  • linux系统查历史cpu使用数据(使用sar 查询cpu和网络占用最近1个月历史数据)。
  • Edge浏览器加载ActiveX控件
  • BUG与测试用例设计
  • 怎么在使用select2时,覆盖layui的下拉框样式
  • MacOSM1 配置Miniconda环境,并设置自启动
  • poi库简单使用(java如何实现动态替换模板Word内容)
  • 机器人开源调度系统OpenTcs6二开-车辆表定义
  • 麦歌恩MT6521-第三代汽车磁性角度传感器芯片
  • 【数据结构】堆,优先级队列
  • 2024 暑假友谊赛 2
  • c++ 线程
  • 【SpringBoot】URL映射之consumes和produces匹配、params和header匹配
  • vscode配置django环境并创建django项目(全图文操作)
  • (一)延时任务篇——延时任务的几种实现方式概述
  • 每天五分钟计算机视觉:目标检测模型从RCNN到Fast R-CNN的进化
  • 环境变量配置文件中两种路径添加方式
  • 开放系统互连安全体系结构学习笔记总结
  • linux搭建redis cluster集群
  • 瀚高数据库初级考试认证
  • 【java基础】spring中使用到的设计模式
  • 浅层深度学习的概述
  • 如何找到最快解析速度的DNS
  • 【YashanDB知识库】数据库使用shutdown immediate无响应导致coredump
  • web前端 React 框架面试200题(一)
  • 【前端】JavaScript入门及实战91-95
  • vue3在元素上绑定自定义事件弹出虚拟键盘
  • VMware 上安装 CentOS 7 教程 (包含网络设置)
  • 算法 day4 【双指针、快慢指针、环形链表】链表下