React Router v6报错:<div>非<Route>组件,<Routes>子组件仅允许Route或React.Fragment
问题原因
react-router-dom v6 对element属性传入
另外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
相关产品推荐
相关产品推荐

