我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了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;
改变
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
<Switch>
<Route path="/home" component={Home} />
</Switch>
to
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
<Routes>
<Route path="/home" element={ <Home />} />
</Routes>
第一步:升级到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及其语法的最新版本,而不是倒退。