简体   繁体   English

错误“错误:A<route> 只能被用作<routes>元素”</routes></route>

[英]Error "Error: A <Route> is only ever to be used as the child of <Routes> element"

I am trying to use routing for the first time and followed the exact instructions from Udemy :我第一次尝试使用路由并遵循Udemy的确切说明:

File App.js :文件App.js

import { Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div>
            <Route path = "/welcome">
                <Welcome />
            </Route>
            <Route path = "/game">
                <Game />
            </Route>
            <Route path = "/leaderboard">
                <Leaderboard />
            </Route>
        </div>
    );
}

export default App;

File index.js文件index.js

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById('root')
);

I get the following error:我收到以下错误:

Error: A Route is only ever to be used as the child of element, never rendered directly.错误:路由只能用作元素的子元素,从不直接渲染。 Please wrap your Route in a Routes.请将您的路线包装在路线中。

Where have I gone wrong?我哪里出错了?

Yes, in react-router-dom version 6 it is a bit different.是的,在 react-router-dom 版本 6 中它有点不同。 Please look as the sample below.请看下面的示例。

React Router tutorial 反应路由器教程

import { render } from "react-dom";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import App from "./App";
import Expenses from "./routes/expenses";
import Invoices from "./routes/invoices";

const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="expenses" element={<Expenses />} />
      <Route path="invoices" element={<Invoices />} />
    </Routes>
  </BrowserRouter>,
  rootElement
);

There was a fairly decent change between versions 5 and 6 of react-router-dom . react-router-dom版本 5 和 6 之间有相当大的变化。 It appears that the Udemy course/tutorial is using version 5 where all you needed was a Router to provide a routing context and Route components just needed to be rendered within this context.似乎 Udemy 课程/教程使用的是版本 5,您只需要一个Router来提供路由上下文,而Route组件只需要在此上下文中呈现。 In version 6, however, the Route components now need to be rendered within a Routes component ( which is an upgrade from the v5 Switch component ).然而,在版本 6 中, Route组件现在需要在Routes组件中呈现(这是从 v5 Switch组件升级而来的)。

Introducing Routes 介绍Routes

One of the most exciting changes in v6 is the powerful new <Routes> element. v6 中最令人兴奋的变化之一是强大的新<Routes>元素。 This is a pretty significant upgrade from v5's <Switch> element with some important new features including relative routing and linking, automatic route ranking, and nested routes and layouts.这是对 v5 的<Switch>元素的一个非常重要的升级,具有一些重要的新功能,包括相对路由和链接、自动路由排名以及嵌套路由和布局。

The error message is pretty clear, wrap your Route components in a Routes component.错误消息非常清楚,将您的Route组件包装在Routes组件中。 The routes also don't take children, they render the components as JSX on the new element prop.路由也不包含子元素,它们将组件呈现为新element属性上的JSX

function App() {
  return (
    <div>
      <Routes>
        <Route path="/welcome" element={<Welcome />} />
        <Route path="/game" element={<Game />} />
        <Route path="/leaderboard" element={<Leaderboard />} />
      </Routes>
    </div>
  );
}

The problem is your react-router-dom version.问题是您的 react-router-dom 版本。

Probably it's 5.1 or higher.可能是5.1或更高。

You can try (in terminal):您可以尝试(在终端中):

npm install react-router-dom@5.3.0

And then your code will be OK.然后你的代码就可以了。 Or you better rebuild your code according to new react-router-dom.或者你最好根据新的 react-router-dom 重建你的代码。

import React from 'react'
import {BrowserRouter, Route, Routes } from 'react-router-dom'
import './App.css';


import Navbar from './components/Navbar';
import { Home } from './components/screens/Home';
import { Login } from './components/screens/Login';
import { Profile } from './components/screens/Profile';
import { Signup } from './components/screens/Signup';

function App() {
  return (
    <BrowserRouter>
    <Navbar />
    <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/signup" element={<Signup />} />
        <Route path="/profile" element={<Profile />} />\
    </Routes>




    </BrowserRouter>


  );
}

export default App;

Try to wrap your routes by Routes :尝试通过Routes包装您的路线:

import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div>
          <Routes>
            <Route path = "/welcome">
                <Welcome />
            </Route>
            <Route path = "/game">
                <Game />
            </Route>
            <Route path = "/leaderboard">
                <Leaderboard />
            </Route>
           </Routes>
        </div>
    );
}

export default App;

In the latest version of React, 'Switch' is replaced with ' Routes ' and 'component' is replaced with ' element '在最新版本的 React 中,“Switch”被替换为“ Routes ”,“component”被替换为“ element

Enter image description here在此处输入图像描述

I think there are many problems that can lead to that issue.我认为有很多问题会导致这个问题。

  1. react-router-dom version 6 no longer supports the use of components directly, use an element to specify component you route. react-router-dom 版本 6 不再支持直接使用组件,使用一个元素来指定你路由的组件。

  2. Route has to be a child of Routes Route 必须是 Routes 的子节点

Use the simple snippet使用简单的代码片段

 import logo from './logo.svg'; import './App.css'; import Navbar from './components/Navbar'; import {BrowserRouter, Routes, Route, Link} from 'react-router-dom'; import Homescreen from './screens/Homescreen'; function App() { return ( <div className="App"> <Navbar/> <BrowserRouter> <Routes> <Route path='/home' element={<Homescreen/>} /> </Routes> </BrowserRouter> </div> ); } export default App;

It's probably because you are using version 6 or higher of react-router-dom.这可能是因为您使用的是 react-router-dom 版本 6 或更高版本。 Try: npm i react-router-dom@5.2.0 And it should work.试试: npm i react-router-dom@5.2.0它应该可以工作。

The problem right here is that you are using React v5.这里的问题是您使用的是 React v5。 Since Reacty v6, several changes were included in Router.从 Reacty v6 开始,Router 中包含了一些更改。 So now, to make it work, and as your error message says, you need to wrap your Route element inside a Routes element (Routes now is the equivalent but improved version of Switch element).所以现在,为了让它工作,正如你的错误消息所说,你需要将你的 Route 元素包装在一个 Routes 元素中(Routes 现在是 Switch 元素的等效但改进版本)。 Also, you need to add an "element" prop that accepts JSX instead of wrapping inside the Route element.此外,您需要添加一个接受 JSX 而不是包装在 Route 元素内的“元素”道具。 So, to make it work, you need to import all these elements like this:因此,要使其正常工作,您需要像这样导入所有这些元素:

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

That being said, your code should look like this:话虽如此,您的代码应如下所示:

    <Router>
        <Routes>
            <Route path="/" element={<Welcome/>}>           
            </Route>
            <Route path="/" element={<Game />}>         
            </Route>
            <Route path="/" element={<Leaderboard />}>          
            </Route>
        </Routes>
    </Router>

In the newer version of react-router-dom , we need to nest the Route inside the Routes .在较新版本的react-router-dom中,我们需要将Route嵌套在Routes中。 Also, component and exact have been removed in newer version.此外, componentexact已在较新版本中删除。

I was getting the same error so I went and added in the Routes like so:我遇到了同样的错误,所以我去添加了路由,如下所示:

import React from "react";
import { connect } from 'react-redux';
import {Routes, Route} from "react-router-dom"
import TripForm from "../componenets/TripForm";
import Trips from "../componenets/Trips"
import { fetchTrips } from "../actions/fetchTrips";


class TripsContainer extends React.Component {

    componentDidMount() {
        this.props.fetchTrips()
    }

    render() {
        return (
            <div>
            <Routes >
                <Route path="/trips/new"  />
                <TripForm /> <br/><br/>
                <Trips trips={this.props.trips} />
            </Routes>
            </div>
        )
    }
}

but I am now getting a new error I cant figure out:但我现在遇到了一个我无法弄清楚的新错误:

Error: [undefined] is not a component.错误:[未定义] 不是组件。 All component children of must be a or <React.Fragment>的所有子组件必须是 a 或 <React.Fragment>

anyone know how to fix this?有人知道怎么修这个东西吗?

Now, React uses "React Router Version 6".现在,React 使用“React Router Version 6”。

For React Router Version 6 , your "index.js" is correct:对于React Router Version 6 ,您的“index.js”是正确的:

index.js : index.js

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from "./App";

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById('root')
);

But your "App.js" is not correct for React Router Version 6 so this is the correct one below:但是你的“App.js”对于React Router 版本 6是不正确的,所以下面是正确的:

* I changed 3 parts as shown below *我更改了 3 个部分,如下图所示

App.js :应用程序.js

  // 1. "Routes" is imported
import { Routes, Route } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div> // 2. With "<Routes></Routes>", surround "3 <Route /> tags" 
            <Routes> // 3. Put an element with a component to each "<Route />" 
                <Route path = "/welcome" element={<Welcome />} />
                <Route path = "/game" element={<Game />} />
                <Route path = "/leaderboard" element={<Leaderboard />} />
            </Routes>
        </div>
    );
}

export default App;

I was unable to import Routes or Switch from react-router-dom:我无法从 react-router-dom 导入 Routes 或 Switch:

Attempted import error: 'Switch' is not exported from 'react-router-dom'.尝试导入错误:“开关”未从“react-router-dom”导出。

But i was installed react-router-dom normally.但是我正常安装了react-router-dom。 any clues?任何线索?

Use:利用:

<div>
  <Header />
</div>
<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/profile" element={<Profile />} />
  <Route path="/about" element={<About />} />
</Routes>

Use the element option to set your component instead of nesting it into the route tags.使用 element 选项来设置您的组件,而不是将其嵌套到路由标签中。 Then wrap all the routes with <Routes></Routes> .然后用<Routes></Routes>包装所有路由。

Do not forget to add Routes to your imports不要忘记将路线添加到您的导入中

import { Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
    return (
        <div>
            <Routes>
              <Route path = "/welcome" element={<Welcome />}/>
              <Route path = "/game" element={<Game />}/>
              <Route path = "/leaderboard" element={<Leaderboard />}/>
            </Routes>          
        </div>
    );
}

export default App;

Even I have faced the same issue, but I found the solution.即使我遇到了同样的问题,但我找到了解决方案。 We need to read the latest document.我们需要阅读最新的文件。 Switch has changed to Routes.开关已更改为路线。 Component of the older version has been replaced with element.旧版本的组件已替换为元素。 We need to include that in the import statement.我们需要将其包含在导入语句中。

If you observe the latest documentation,如果您观察最新的文档,

I was facing the same issue and solved it.我面临同样的问题并解决了它。 Though I am using虽然我正在使用

react-router-dom@6

So I had to modify app.js and index.js like below.所以我不得不修改app.jsindex.js ,如下所示。

In index.jsindex.js

import { BrowserRouter } from "react-router-dom";

<React.StrictMode>
  <BrowserRouter>
    <App />
  </BrowserRouter>
</React.StrictMode>

And app.jsapp.js

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

function App() {
  return (
    <>
      <Header />
        <main className="py-3">
          <Container>
            <Routes>
              <Route path="/" element={<HomeScreen />} exact/>
            </Routes>
          </Container>
        </main>
      <Footer />
    </>
  );
}

export default App;

According to theofficial documentation .根据官方文档

I know I'm late but there is another way to do nested routes straight from javascript.我知道我迟到了,但还有另一种方法可以直接从 javascript 进行嵌套路由。

first import首次进口

import { useRoutes } from "react-router-dom";

secondly, declare your routes.其次,声明你的路线。 Here is a quick example这是一个简单的例子

function App() {

return useRoutes([
{
  path: "/",
  element: <Example/>
},
{
  path: "/contact",
  element: <Example/>
}]);

} }

so now you can have unlimited nested components doing it this way.所以现在你可以用这种方式拥有无限的嵌套组件。

There is another way to fix the version issues:还有另一种解决版本问题的方法:

App.js File: App.js 文件:

import { BrowserRouter, Route, Routes } from "react-router-dom";
import Welcome from "./Pages/Welcome";
import Game from "./Pages/Game";
import Leaderboard from "./Pages/Leaderboard";

function App() {
  return (<div>
  <BrowserRouter>
    <Routes>
            <Route path = "/Welcome" element={< Welcome/>}/>
            <Route path = "/Game" element={< Game/>}/>
            <Route path = "/LeaderBoard" element={< LeaderBoard/>}/>
           </Routes>
  </BrowserRouter>
    </div>
  );
}

export default App;

Index.js file:索引.js 文件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 路由错误-A<route> 只能用作的孩子<routes>元素,从不直接渲染。 请把你的<route>在一个<routes></routes></route></routes></route> - Route Error- A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes> 路线只能用作的孩子<routes>元素,在 React 路由器 v6 中</routes> - A Route is only ever to be used as the child of <Routes> element, in React router v6 反应路由器用作的孩子<Routes>元素错误 - react router to be used as the child of <Routes> element error 子路由中的routerLink错误 - routerLink error in child route 错误是:A<Router> 可能只有一个子元素 - Error is: A <Router> may have only one child element JavaScript For循环附加子元素仅附加第一个元素,然后引发错误 - Javascript For loop appending child only appends first element, then throws error 将儿童路线嵌套在另一条儿童路线内 - Nesting child routes within another child route Angular 2和SystemJS子路由访问错误 - Angular 2 and SystemJS child route access error 子元素按类名错误 - Child element by class name error 添加新路由时出错,路由配置中需要路径 - Getting error while adding new routes, path is required in a route configuration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM