开发者问题收集

尝试导入错误:“Switch”未从“react-router-dom”导出

2020-07-27
1065617

我不知道为什么会出现此错误,而且我在任何地方都找不到答案。我已卸载 react-router-dom 软件包并重新安装,但它仍告诉我 switch 模块未从 react-router-dom 导出。这是我的代码。

我收到的错误:

Attempted import error: 'Switch' is not exported from 'react-router-dom'.

代码

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;
3个回答

react-router-dom v6 中,“Switch” 被路由“Routes”取代。您需要将导入从

import { Switch, Route } from "react-router-dom";

更新为

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

您还需要将 Route 声明从

<Route path="/" component={Home} />

更新为

<Route path='/' element={<Home/>} />

react-router-dom 中,您也不需要在 Route 声明中使用 exact

有关更多信息,您可以访问官方文档: 升级到 react-router-dom v6

prabhat kumar jena
2021-11-05

如果您使用的是 react-router-dom v6,则 Switch 似乎已被 Routes 取代。

luke.mas
2021-05-05

这是一个使用 react-router-dom V6 的示例

import React from 'react'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'

import '../styles/global.css'

import Layout from '../containers/Layout'
import Home from '../pages/Home'
import Login from '../containers/Login'
import RecoveryPassword from '../containers/RecoveryPassword'
import NotFound from '../pages/NotFound'

const App = () => {
  return (
    <Router>
      <Layout>
        <Routes>
          <Route exact path="/" element={<Home/>}/>
          <Route exact path="/login" element={<Login/>}/>
          <Route exact path="/recovery-password" element={<RecoveryPassword/>}/>
          <Route path="*" element={<NotFound/>}/>
        </Routes>
      </Layout>
    </Router>
  );
}

export default App;
Jean Leon
2021-11-08