我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了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;
export 'Switch'(作为'Switch'导入)在'react-router-dom'中找不到
第一种方法[用路由替换交换机]
import { Routes , Route , Link } from 'react-router-dom';
<Routes>
<Route exact path='/'>
<HomePage />
</Route>
</Routes>
第二种方法[将react-router-dom版本降级至版本5或以下]
npm i react-router-dom@5.0.0
第一步:升级到React 16.8+和React -router-dom v5.2:
npm uninstall react-router-dom
npm install react-router-dom@5.2
步骤2:更新react-router-dom导入语句。
修改import {Switch, Route} from "react-router-dom";:
import { Routes, Route } from 'react-router-dom';
第三步:升级语法,把“Switch”换成“Routes”,把“component”换成“element”
改变
<Switch>
<Route path="/home" component={HomePage} />
</Switch>
to
<Routes>
<Route path="/home" element={<HomePage/>} />
</Routes>
或者,您也可以按照其他解决方案中的建议降低react-router版本。
但是,我建议升级到react-router-dom及其语法的最新版本,而不是倒退。
语法已经改变
旧的语法
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
<Switch>
<Route path="/home" component={Home} />
</Switch>
新语法:
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
<Routes>
<Route path="/home" element={<Home/>} />
</Routes>