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>
相关推荐
开开心心就好2 天前
发票合并打印工具,多页布局设置实时预览
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节
开开心心就好7 天前
开源免费高速看图工具,支持漫画大图秒开
linux·运维·服务器·安全·ruby·symfony·1024程序员节
unable code10 天前
磁盘取证-Flying_High
网络安全·ctf·misc·1024程序员节·磁盘取证
unable code10 天前
磁盘取证-ColorfulDisk
网络安全·ctf·misc·1024程序员节·内存取证
unable code11 天前
磁盘取证-[第十章][10.1.2 磁盘取证方法]磁盘取证1
网络安全·ctf·misc·1024程序员节·内存取证
开开心心就好13 天前
免费抽奖工具支持批量导入+自定义主题
linux·运维·服务器·macos·pdf·phpstorm·1024程序员节
开开心心就好17 天前
卸载工具清理残留,检测垃圾颜色标识状态
linux·运维·服务器·python·安全·tornado·1024程序员节
子燕若水18 天前
Facebook reels 运营指南
1024程序员节
尘觉21 天前
创作 1024 天|把热爱写成长期主义
数据库·1024程序员节
写点什么呢22 天前
Word使用记录
word·1024程序员节