新版本的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>