【问题标题】:Module not found: Can't resolve 'react-route-dom' I tried alot but not able to solve找不到模块:无法解析“react-route-dom”我尝试了很多但无法解决
【发布时间】:2022-01-21 04:12:08
【问题描述】:

我解决了错误模块未找到但在此之后 Switch没有出现导出错误。

我将 Switch 更改为 Routes 但出现错误

App.js

import Chat from './Chat';
import React from "react";
import ReactDOM from "react-dom";
import { Router, Routes, Route,Switch } from "react-router-dom";

function App() {
  return (

    <Router>
      <Routes>

    <div className="App">
      
        <div className="App_body">
              {/*Sidebar*/}
              <Sidebar/>
           
              {/*Chat*/}
              <Chat/>
              
       </div>
      
    </div>
    </Routes>
    </Router>  
  );
}

export default App;
  

【问题讨论】:

  • 现在面临这个错误 TypeError: Cannot read properties of undefined (reading 'pathname')
  • Router,请看下面我的回答。

标签: reactjs react-native


【解决方案1】:
TypeError: Cannot read properties of undefined (reading 'pathname')

这是由于导入和使用低级 Router 组件引起的。

Router

declare function Router(
  props: RouterProps
): React.ReactElement | null;

interface RouterProps {
  basename?: string;
  children?: React.ReactNode;
  location: Partial<Location> | string;
  navigationType?: NavigationType;
  navigator: Navigator;
  static?: boolean;
}

它需要传递 locationnavigator 属性。

除非您需要自定义路由器/等...然后建议使用更高级别的路由器。

&lt;Router&gt;是所有路由器共享的低级接口 组件(&lt;BrowserRouter&gt;&lt;HashRouter&gt;&lt;StaticRouter&gt;&lt;NativeRouter&gt;&lt;MemoryRouter&gt;)。就 React 而言,&lt;Router&gt; 是 提供路由信息给其余部分的上下文提供程序 应用程序。

您可能永远不需要手动渲染&lt;Router&gt;。相反,你 应该使用更高级别的路由器之一,具体取决于您的 环境。在给定的应用中,您只需要一个路由器。

例子:

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

function App() {
  return (
    <Router>
      <Routes>
        ... all your Route components ...
      </Routes>
    </Router>  
  );
}

【讨论】:

    【解决方案2】:

    您在 useParams 导入中缺少 r

    【讨论】:

    • TypeError: Cannot read properties of undefined (reading 'pathname')
    • 现在面临这个错误 TypeError: Cannot read properties of undefined (reading 'pathname')
    【解决方案3】:

    您的代码没有编译,因为您有错字。

    您正在从“react-route-dom”而不是“react-router-dom”导入 useParams。

    只需更改它,它应该可以编译。

    【讨论】:

    • 现在面临这个错误 TypeError: Cannot read properties of undefined (reading 'pathname')
    • 我认为定义您的 Routes 配置存在问题。你能把它的代码贴出来让我们仔细看看吗?这是他们在文档中的做法link
    猜你喜欢
    • 2022-06-23
    • 2020-10-13
    • 2017-07-23
    • 2022-06-16
    • 2017-12-21
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多