我不知道为什么我得到这个错误,我在任何地方都找不到答案。我已经卸载了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的新手。
以下是我的App.js代码(类基组件):
import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Navbar from './components/Navbar';
import News from './components/News';
import { BrowserRouter as Router, Route, Routes,Link } from 'react-router-dom'
export class App extends Component {
static propTypes = {
}
render() {
return (
<>
<Navbar/>
<Router>
<Routes>
<Route path="/general"><News pageSize={3} country={'us'} category={'general'}/></Route>
</Routes>
</Router>
</>
)
}
}
export default App
你必须先检查npm包的版本。
执行npm info react-router-dom version命令查看。
如果包版本为>= 6.0.0,则必须进行更改
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
to
import { BrowserRouter as Router,Routes, Route, Link } from "react-router-dom";
也必须改变
<Route path="/home" component={Home} />
to
<Route path="/home" element={<Home/>} />