React-Route新版本(v6或以上)用法示例

新版本的React-Route (v6或以上,但不排序后续版本还会有修改),移除了Switch,写法和老版本有一些区别,下面分享一个示例:

JSX文件:

javascript 复制代码
import React, {StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter as Router, Route, Routes ,Link } from "react-router-dom";
import Home from './components/Home';    //根据路由显示的子组件,自己定义
import About from './components/About';  //根据路由显示的子组件,自己定义

//路由 begin
export function Navigation() {
return (
        <nav>
          <ul>
              <li>
                  <Link to="/">首页</Link>
              </li>
              <li>
                  <Link to="/about">关于</Link>
              </li>
          </ul>
        </nav>
      )
}

export default function App() {
  return (
    <Router>
         <Navigation />
        <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
        </Routes>
    </Router>
    )
}
//路由 end

//错误边界
class ErrorBoundary extends React.Component {
  constructor(props){
    super(props)
    this.state = { hasError: false }
  }

  static getDerivedStateFromError(error){
    return {hasError:true}
  }

  componentDidCatch(error, info){
    console.log(error, info)
  }

  render(){ 
    if(this.state.hasError){  
      return <h1>Something went wrong.</h1>
    } 
    return this.props.children
  }
}

let root = document.getElementById('root')

if(!root) 
{
  root.render(
    <StrictMode>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </StrictMode>
  )
}

入口html页面引用上面的jsx文件,比如

html 复制代码
<script type="module" src="/src/main.jsx"></script>
相关推荐
✿ ༺ ོIT技术༻6 天前
Linux:TCP和守护进程
linux·运维·服务器·网络·tcp/ip·1024程序员节
辅助东皇燕双鹰10 天前
行测知识()
1024程序员节
深蓝易网13 天前
探寻制造型企业MES管理系统:功能、架构与应用全解析
大数据·运维·人工智能·架构·制造·1024程序员节
Lenyiin18 天前
2848、与车相交的点
c++·算法·leetcode·1024程序员节
earthzhang202123 天前
《深入浅出HTTPS》读书笔记(31):HTTPS和TLS/SSL
开发语言·网络·python·https·1024程序员节
不讲废话的小白25 天前
怎么样把pdf转成图片模式(不能复制文字)
pdf·1024程序员节
明明真系叻1 个月前
2025.1.26机器学习笔记:C-RNN-GAN文献阅读
人工智能·笔记·深度学习·机器学习·生成对抗网络·1024程序员节
Joeysoda1 个月前
Java数据结构 (从0构建链表(LinkedList))
java·linux·开发语言·数据结构·windows·链表·1024程序员节
清风-云烟1 个月前
使用redis-cli命令实现redis crud操作
java·linux·数据库·redis·spring·缓存·1024程序员节
Joeysoda1 个月前
Java数据结构 (链表反转(LinkedList----Leetcode206))
java·linux·开发语言·数据结构·链表·1024程序员节