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

React Router v6报错:<div>非<Route>组件,<Routes>子组件仅允许Route或React.Fragment

问题原因

react-router-dom v6 对组件的语法做了破坏性更新,所有要渲染的内容都必须通过element属性传入,不能直接将组件、DOM元素作为的子节点使用,这就是你触发报错的核心原因。
另外v6中默认开启路径精确匹配,不需要额外加exact属性,该属性已经被废弃。

修正后的完整代码

import React, { useState } from "react";
import Counters from "./Counters";
import Navi from "./Navbar";
import Textbox from "./Textbox";
import About from "./About";
import Alerts from "./Alerts";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
const App = () => {
  // 原代码注释了alert的状态定义,直接用alert变量会报错,这里放开注释
  const [alert,setalert]=useState()
  const Showalert=(message,type)=>{
      setalert({
          msg: message,
          typ: type,
      })
  }
  return (
    <React.Fragment>
      <Navi></Navi>
      <Alerts className="container" alrt={alert} />
      <Router>
        <Routes>
          {/* 把要渲染的内容放到element属性里,用{}包裹 */}
          <Route path="/" element={
            <div className="container my-3">
              <Textbox head="Enter Your Text here..." />
            </div>
          } />
          {/* 移除废弃的exact属性,About组件也放到element里 */}
          <Route path="/About" element={<About></About>} />
        </Routes>
      </Router>
     
    </React.Fragment>
  );
};
export default App;

额外注意点

  • 如果后续Navi、Alerts组件需要用到路由相关hooks(比如useNavigate、useParams等),需要把它们挪到标签内部,否则无法调用路由能力

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:54:06