You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router报错求助:跟随教程编写代码却出现控制台错误

Fixing React Router: " is only ever to be used as the child of element" Error

Hey there, let's sort out this error you're running into. The first error message lays out the issue clearly: your <Route> components must be wrapped inside a <Switch> component—you can't render them directly under a <div> like you are right now.

Looking at your App.js code, there are two key fixes needed:

  1. Your <Route> elements aren't wrapped in <Switch> (which is exactly what the error is complaining about)
  2. The root path (/) is missing the exact prop, which would cause it to match every URL (since all paths start with /)

Here's the corrected version of your App.js:

import React from 'react';
import './App.css';
import HomePage from './Components/HomePage/HomePage'
import WhoWeHelp from './Components/WhoWeHelpPage/WhoWeHelp';
import {BrowserRouter as Router , Switch , Route} from 'react-router-dom'

function App() {
  return (
    <Router>
      <div className="App">
        <Switch>
          {/* Add 'exact' to ensure this only matches the root URL */}
          <Route exact path="/" component={HomePage} />
          <Route path="/whowehelp" component={WhoWeHelp} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

What these changes do:

  • <Switch> component: This component loops through its child <Route>s and renders only the first one that matches the current URL. This stops multiple routes from rendering at the same time, which is a common pitfall.
  • exact prop: Without this, the / route would trigger even when you visit /whowehelp (since / is a prefix of that path). Adding exact ensures it only renders when the URL is exactly /.

After making these adjustments, both of your console errors should disappear.

内容的提问来源于stack exchange,提问作者codingknack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:22:33