【问题标题】:Failed to compile - Attempted import error: 'Switch' is not exported from 'react-router-dom' [closed]编译失败 - 尝试导入错误:“Switch”未从“react-router-dom”导出 [关闭]
【发布时间】:2022-01-01 22:05:39
【问题描述】:

以下是我的 App.js 文件,我正在研究基于类的组件

import "./App.css";

import React, { Component } from "react";
import NabBar from "./components/NabBar";
import News from "./components/News";
import Spinner from "./components/Spinner";
import { Routes, Route, Router,Switch } from "react-router-dom";

export default class App extends Component {
  render() {
    return (
      <div>
        <Router>
          <NabBar />
          <Switch>
            <Route path="/">
              <News pageSize={3} country={"us"} category={"general"} />
            </Route>
            <Route path="/business">
              <News pageSize={3} country={"us"} category={"business"} />
            </Route>
          </Switch>
        </Router>
      </div>
    );
  }
}

我尝试了很多方法,但无法解决这个问题。

【问题讨论】:

  • 您安装了react-router-dom 的哪个版本?您尝试了哪些具体的事情?
  • 是的,我已经安装了 react-router-dom
  • 哪个版本?
  • “react-dom”:“^17.0.2”,“react-router”:“^6.0.2”,“react-router-dom”:“^6.0.2”,

标签: javascript reactjs react-router create-react-app


【解决方案1】:

&lt;Switch&gt; 在版本 6 中已替换为 &lt;Routes&gt;。我还将 Router 更改为 BrowserRouter 并将组件传递为 elements

如果你想使用Router,你可以这样做:

import { Routes, Route, BrowserRouter as Router } from "react-router-dom";

示例:

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

export default class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <NabBar />
          <Routes>
            <Route path="/" element={<News pageSize={3} country={"us"} category={"general"}} />
            <Route path="/business" element={<News pageSize={3} country={"us"} category={"business"}} />
          </Routes>
        </BrowserRouter>
      </div>
    );
  }
}

【讨论】:

  • TypeError: 无法读取未定义的属性(读取“路径名”)路由器 E:/packages/react-router/index.tsx:281 278 | 279 | 280 |让 { > 281 |路径名 = "/", | ^ 282 |搜索 = "", 283 |哈希 = "", 284 |状态=空,
  • 应用您的解决方案后立即出现此错误
  • 完成但还是同样的问题
  • 另外Router 应该是BrowserRouter 我认为你应该将组件作为element 传递
【解决方案2】:

要解决这个问题,请遵循 React Router v6 文档 react-router-v6 要么 用以前的版本重新安装 react-router-dom

npm install react-router-dom@5.3.0

【讨论】:

  • 谢谢,但没用
猜你喜欢
  • 2020-11-17
  • 2022-01-12
  • 2022-01-21
  • 2023-03-11
  • 2021-04-14
  • 2020-11-01
  • 2020-04-26
  • 2020-02-12
相关资源
最近更新 更多