我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了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

其他回答

改变

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>

写入<路由>而不是<交换机>。

在终端中运行:

npm install --save react-router react-router-dom

这对我很有帮助。或检查文件包。在“react-dom”后面添加以下内容:“^17.0.2”,

 "react-router": "^6.0.0",
import React from "react";
import { Link, BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./App.css";
import App from "./App";
const RouterPage = () => {
    return (
        <Router>
            <div>
                <nav>
                    <Link to="/">Home</Link>
                    <Link to="/posts">Posts</Link>
                    <Link to="/">About</Link>
                    <Link to="/contact">Contact</Link>
                </nav>
                <Routes>
                    <Route exact path="/" element={<App />}></Route>
                    <Route path="/post" element={<App />} />
                    <Route path="/about" element={<App />} />
                    <Route path="/contact" element={<App />} />
                </Routes>
            </div>
        </Router>
    );
};

你应该把Switch换成Routes

我是这样解决的:

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

我也有同样的问题。在项目终端上,输入以下命令。您不需要对代码进行任何更改。

卸载NPM react-router-dom NPM安装react-router-dom@5.2.0