我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了react-router-dom包并重新安装了它,但它仍然告诉我交换模块没有从react-router-dom导出。这是我的代码。
我得到的错误是:
试图导入错误:“Switch”没有从“react-router-dom”中导出。
Code
import React from 'react';
import './App.css';
import NavBar from './components/navbar.js';
import Footer from './components/footer.js';
import Home from './components/pages/homepage/home.js';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div className="app-container">
<NavBar />
<Switch>
<Route path="/home" component={Home} />
</Switch>
<Footer />
</div>
</Router>
);
}
export default App;
在react-router-dom v6中,开关被路由替换。下面是配置react-router-dom v6的简单示例。
import * as React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Layout from './components/Layout';
import ProtectedRoute from './components/ProtectedRoute';
import LoginPage from './pages/LoginPage';
import WizardPage from './pages/WizardPage';
import RequestsPage from './pages/RequestsPage';
import './App.scss'
export class App extends React.Component {
public render() {
const sharedRouteProps = { exact: true, authenticationPath: '/login' };
const wizardRouteProps = { ...sharedRouteProps, path: "/", component: WizardPage };
const requestsRouteProps = { ...sharedRouteProps, path: "/requests", component: RequestsPage };
return (
<Layout>
<Router>
<Switch>
<Route exact path='/login' component={LoginPage} />
<ProtectedRoute {...wizardRouteProps} />
<ProtectedRoute {...requestsRouteProps} />
</Switch>
</Router>
</Layout>
);
}
}
如果你正在使用react-router-dom v6,你必须改变Switch到Routes,如下面的例子所示:
而不是导入Switch,
import {Switch,…} from 'react-router-dom';
进口航线
import{路由,…} from 'react-router-dom';
然后,不要使用component ={ComponentName},而是使用element={<ComponentName/>},如下所示:
import { Routes, Route, ...} from 'react-router-dom';
.
.
.
<Routes>
<Route exact path='/' element={<Home/>}></Route>
</Routes>
在react-router-dom v6中,“Switch”被替换为路由“routes”。您需要更新从的导入
import { Switch, Route } from "react-router-dom";
to
import { Routes ,Route } from 'react-router-dom';
您还需要更新Route声明
<Route path="/" component={Home} />
to
<Route path='/' element={<Home/>} />
在react-router-dom中,你也不需要在Route声明中使用exact。
欲了解更多信息,请访问官方文档:
升级到react-router-dom v6