我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了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;
我解决了我的错误,通过改变我渲染我的路线使用元素的方式。
To:
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Home } from "./app";
import { Login, Register } from "./auth";
const R: React.FC = () => {
return (
<Router>
<Routes>
<Route path="/login" caseSensitive={false} element={<Login />} />
<Route path="/register" caseSensitive={false} element={<Register />} />
<Route path="/" caseSensitive={false} element={<Home />} />
</Routes>
</Router>
);
};
export default R;
基本上在v6之前。*:
import React from "react";
import { BrowserRouter as Router, Route, Switch} from "react-router-dom";
import { Home } from "./app";
import { Login, Register } from "./auth";
const R: React.FC = () => {
return (
<Router>
<Switch>
<Route path="/login">
<Login />
</Route>
<Route path="/register">
<Register/>
</Route>
<Route path="/">
<Home/>
</Route>
</Switch>
</Router>
);
};
export default R;
在v6 . *
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Home } from "./app";
import { Login, Register } from "./auth";
const R: React.FC = () => {
return (
<Router>
<Routes>
<Route path="/login" caseSensitive={false} element={<Login />} />
<Route path="/register" caseSensitive={false} element={<Register />} />
<Route path="/" caseSensitive={false} element={<Home />} />
</Routes>
</Router>
);
};
export default R;
在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
我和杂志海报上的人面临着同样的问题。我尝试了以下所有的方法:
卸载并安装react-router-dom
分别从react-router-dom导入Switch
但对我来说什么都没用。
请遵循以下指示。我相信你不会再得到错误。
正确的代码:
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, Routes, Route, Link } from "react-router-dom";
function App() {
return (
<Router>
<div className="app-container">
<NavBar />
<Routes>
<Route path="/home" element={<Home/>} />
</Routes>
<Footer />
</div>
</Router>
);
}
export default App;
注意:Switch已经被替换为Routes,我们需要使用element而不是component。