React 路由无法读取导航上的路径名属性

发布于 2025-01-19 09:22:07 字数 2710 浏览 0 评论 0原文

我最近开始使用 React 开发前端应用程序,并且拥有一点 React-Native 编程经验。 为了提高我对 React 的了解,我学习了官方文档并学习了 udemy 课程。 因此,我正在构建一个小型测试应用程序,在其中使用反应路由(遵循我们在 udemy 课程中看到的内容)。 但是,我有以下与路由相关的错误(我附上错误屏幕)

在此处输入图像描述

我在网上的堆栈上搜索了可能的解决方案,例如降级react-router-dom,或修改历史声明,但不幸的是我仍然收到此错误,并且我无法理解它来自何处。 您有什么建议或建议吗?

我的应用配置:

  • package.json

  "name": "app1",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.8.1",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "history": "^5.3.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-redux": "^7.2.8",
    "react-router": "^6.3.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

  • paths.js
import React, { Component } from 'react';

import Component1 from './functional/component1';
import Component2 from './functional/component2';
import Component3 from './functional/component3';

//import container home-page
import Container1 from './containers/container1';
import Header from './containers/header';
import history from './utils/history';

//react router import
import { Router, Route } from 'react-router';

class Routes extends Component {
   render() {
      return (
         <div>
            <Router history={history.location} navigator={history} >
               <div>
                  <Header />
                  <Route path="/" component={Container1} />
                  <Route path="/component1" component={Component1} />
                  <Route path="/component2" component={Component2} />
                  <Route path="/component3" component={Component3} />
               </div>
            </Router>
         </div>
      )
   }
}

export default Routes;

-history.js

var createHistory = require('history').createBrowserHistory;
export default createHistory();

I have recently started developing frontend apps with React and I come from a little programming experience with react-native.
To improve my knowledge on react I studied both the official documentation and took courses on udemy.
So I'm building a small test app in which to use react routing (following what we saw in the udemy course).
However, I have the following error related to routing (I attach the error screen)

enter image description here

I have searched here on the stack that online for possible solutions, such as downgrading react-router-dom, or modifying the history declaration, but unfortunately I still get this error and I can't understand what it comes from.
Do you have any suggestions or advice?

My app configuration:

  • package.json

  "name": "app1",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.8.1",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "history": "^5.3.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-redux": "^7.2.8",
    "react-router": "^6.3.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

  • routes.js
import React, { Component } from 'react';

import Component1 from './functional/component1';
import Component2 from './functional/component2';
import Component3 from './functional/component3';

//import container home-page
import Container1 from './containers/container1';
import Header from './containers/header';
import history from './utils/history';

//react router import
import { Router, Route } from 'react-router';

class Routes extends Component {
   render() {
      return (
         <div>
            <Router history={history.location} navigator={history} >
               <div>
                  <Header />
                  <Route path="/" component={Container1} />
                  <Route path="/component1" component={Component1} />
                  <Route path="/component2" component={Component2} />
                  <Route path="/component3" component={Component3} />
               </div>
            </Router>
         </div>
      )
   }
}

export default Routes;

-history.js

var createHistory = require('history').createBrowserHistory;
export default createHistory();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

溇涏 2025-01-26 09:22:07

发行

低级路由器需要与V5中的几个不同的道具。

router

 声明功能路由器(
  道具:routerprops
):React.Reactelement |无效的;

接口routerprops {
  Basename?:字符串;
  儿童?:react.reeactnode;
  位置:部分&lt;位置&gt; |细绳; //&lt;  - 必需
  导航类型?:导航类型;
  导航器:导航器; //&lt;  - 必需
  静态?
}
 

export function Router({
  basename: basenameProp = "/",
  children = null,
  location: locationProp, // <-- undefined location
  navigationType = NavigationType.Pop,
  navigator,
  static: staticProp = false,
}: RouterProps): React.ReactElement | null {
  ...

  let {
    pathname = "/", // <-- cannot read "pathname" of undefined!
    search = "",
    hash = "",
    state = null,
    key = "default",
  } = locationProp;

  ...

  if (location == null) {
    return null;
  }

  return (
    <NavigationContext.Provider value={navigationContext}>
      <LocationContext.Provider
        children={children}
        value={{ location, navigationType }}
      />
    </NavigationContext.Provider>
  );
}

您错误地使用历史 prop而不是位置 prop,这就是为什么位置在组件中不确定并且无法阅读PathName

此外,在react-rout-dom@6 路由组件中必须包装在ROUTES组件中,以使路由路径匹配和渲染工作。

解决方案

传递正确的道具,然后将路由组件包装在路由组件中。

import React, { Component } from 'react';

import Component1 from './functional/component1';
import Component2 from './functional/component2';
import Component3 from './functional/component3';

//import container home-page
import Container1 from './containers/container1';
import Header from './containers/header';
import history from './utils/history';

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

class Routes extends Component {
  render() {
    return (
      <div>
        <Router location={history.location} navigator={history} >
          <div>
            <Header />
            <Routes>
              <Route path="/" component={Container1} />
              <Route path="/component1" component={Component1} />
              <Route path="/component2" component={Component2} />
              <Route path="/component3" component={Component3} />
            </Routes>
          </div>
        </Router>
      </div>
    )
  }
}

Issue

The low-level Router takes a few different props than it did in v5.

Router

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

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

Router source

export function Router({
  basename: basenameProp = "/",
  children = null,
  location: locationProp, // <-- undefined location
  navigationType = NavigationType.Pop,
  navigator,
  static: staticProp = false,
}: RouterProps): React.ReactElement | null {
  ...

  let {
    pathname = "/", // <-- cannot read "pathname" of undefined!
    search = "",
    hash = "",
    state = null,
    key = "default",
  } = locationProp;

  ...

  if (location == null) {
    return null;
  }

  return (
    <NavigationContext.Provider value={navigationContext}>
      <LocationContext.Provider
        children={children}
        value={{ location, navigationType }}
      />
    </NavigationContext.Provider>
  );
}

You are incorrectly using a history prop instead of the location prop, and this is why location is undefined in the component and unable to read a pathname.

Additionally, in react-router-dom@6 the Route components necessarily need to be wrapped in the Routes component in order for route path matching and rendering to work.

Solution

Pass the correct required props and wrap the Route components in Routes component.

import React, { Component } from 'react';

import Component1 from './functional/component1';
import Component2 from './functional/component2';
import Component3 from './functional/component3';

//import container home-page
import Container1 from './containers/container1';
import Header from './containers/header';
import history from './utils/history';

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

class Routes extends Component {
  render() {
    return (
      <div>
        <Router location={history.location} navigator={history} >
          <div>
            <Header />
            <Routes>
              <Route path="/" component={Container1} />
              <Route path="/component1" component={Component1} />
              <Route path="/component2" component={Component2} />
              <Route path="/component3" component={Component3} />
            </Routes>
          </div>
        </Router>
      </div>
    )
  }
}
天冷不及心凉 2025-01-26 09:22:07

您正在使用 react router v6 ,在 v6 中,您必须将所有 route's 包装在 ...< ;/Routes> 标签。

//react router import
import { Router, Route, Routes } from 'react-router'; // Make sure to import ----Routes----

class Routes extends Component {
   render() {
      return (
         <div>
            <Router history={history.location} navigator={history} >
               <div>
                  <Header />
                  <Routes>
                    <Route path="/" component={Container1} />
                    <Route path="/component1" component={Component1} />
                    <Route path="/component2" component={Component2} />
                    <Route path="/component3" component={Component3} />
                  </Routes>
               </div>
            </Router>
         </div>
      )
   }
}

export default Routes;

除了 之外,您不能在 ... 之间添加任何内容。

You are using react router v6 and in v6 you have to wrap all of your route's in <Routes>...</Routes> tag.

//react router import
import { Router, Route, Routes } from 'react-router'; // Make sure to import ----Routes----

class Routes extends Component {
   render() {
      return (
         <div>
            <Router history={history.location} navigator={history} >
               <div>
                  <Header />
                  <Routes>
                    <Route path="/" component={Container1} />
                    <Route path="/component1" component={Component1} />
                    <Route path="/component2" component={Component2} />
                    <Route path="/component3" component={Component3} />
                  </Routes>
               </div>
            </Router>
         </div>
      )
   }
}

export default Routes;

And you can't add anything between <Routes>...</Routes> except <Route />.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文