react路由新写法
最近使用react-router-dom发现Switch无法导入,报错:
'Switch' is not exported from 'react-router-dom'
那是因为 react-router-dom v6版本换了名字,
Switch 换成 Routes
Redirect 换成 useNavigate
在react-router-dom的最新版本中,旧的写法会报错:
//错误的引用方式: 'Switch' is not exported from 'react-router-dom'
import { Switch, Route } from "react-router-dom";
//正确的引用方式
import { Routes ,Route } from 'react-router-dom';
在react官网中搜索路由,里面的示例写法在v6版本中已经不生效了。
下面是react官网路由的旧写法:
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</Switch>
</Suspense>
</Router>
);
在react-router-dom的最新版本中,Route的component属性也换成了element,element的属性值要写成 JSX组件的形式,如:<Home/>
//新的正确写法
import User from "./components/User";
<Route path="/user" element={<User/>}/>
如果 Route直接包含在非Routes的其他元素里,则还会报错:
//错误的写法:
ReactDOM.render(
<Router>
<>
<Route path="/" element={<Home/>}/>
<Route path="/user" element={<User/>}/>
</>
</Router>,
document.getElementById('root')
);
报错:
A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>
所以,Route 只能包在Routes中。
下面是react路由的react-router-dom的最新版本写法的一个完整示例:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Home from "./components/Home";
import User from "./components/User";
ReactDOM.render(
<Router>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/user" element={<User/>}/>
</Routes>
</Router>,
document.getElementById('root')
);