我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了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包最近发生了突破性的变化。React Router v6 Changelog永久链接

所以你所需要的就是重命名导入,就像这样…

import { Routes as Switch, Route } from 'react-router-dom';

干杯!

其他回答

改变

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>

我是这样解决的:

yarn add react-router-dom@5,3,0

如果你正在使用react-router-dom的版本6,那么你需要用路由更新Switch。下面的语法适合我:

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import './App.css';
import Home from './components/Home';

function App() {
  return (
    <div>
      <Router>
        <Routes>
          <Route path="/" exact element={<Home />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Switch是从react-router导出的,而不是从react-router-dom导出的(我认为Route也一样)。

如果你正在使用一个更新版本的react-router-dom(例如,在我的例子中是^6.2.1),你应该将<Switch>更改为<Routes>,并使用<Route>和component={<SampleComponent />}参数。

特别是下面的代码示例:

import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import MyComponent from './containers/MyComponent';

export default function AppRoutes() {
    return (
        <Routes>
            <Route exact path="/" component={<MyComponent />}>
            </Route>
        </Routes>
    );
}