[英]I am not able to use the router in react js
I have been trying to use a router on react project but getting an error :我一直在尝试在 react 项目上使用路由器,但出现错误:
A Route is only ever to be used as the child of Routes element, never rendered directly. Route 只能用作 Routes 元素的子元素,从不直接渲染。 Please wrap your Route in a Routes.请将您的路线包装在路线中。
The Code Is Shown Below代码如下所示
import About from "./container/About";
import Profile from "./container/Profile";
import { useState } from "react";
import {BrowserRouter as Routes,Route} from 'react-router-dom'
function App(){
const [state, setState] = useState('')
return(
<div className="App">
<button onClick={()=>setState('about')}>About</button>
<button onClick={()=>setState('profile')}>Profile</button>
<Routes>
<Route component={About} path='/about'></Route>
</Routes>
</div>
)
}
export default App;
I'm not sure you can call the BrowserRouter
component the way you did in your code.我不确定您是否可以像在代码中那样调用BrowserRouter
组件。 Perhaps if you wrap your code in the router - in a way that it's the topmost parent, such as this example and render your buttons inside of it then it should work fine.也许如果您将代码包装在路由器中 - 以它是最顶层的父级的方式,例如这个示例并在其中呈现您的按钮,那么它应该可以正常工作。
If you're on version 6 of react-router-dom
, you need to name the props differently:如果您使用的是react-router-dom
版本 6,则需要以不同的方式命名道具:
<Route element={About} path='/about'></Route>
In version 5, it was named component
.在版本 5 中,它被命名为component
。
I assume you're on version 6, because I can't remember version 5 having the Routes
component.我假设您使用的是版本 6,因为我不记得版本 5 具有Routes
组件。 Also, you need to import the components differently, and wrap everything with the BrowserRouter.此外,您需要以不同的方式导入组件,并使用 BrowserRouter 包装所有内容。
import About from "./container/About";
import Profile from "./container/Profile";
import { useState } from "react";
import {BrowserRouter, Routes, Route} from 'react-router-dom'
function App(){
const [state, setState] = useState('')
return(
<BrowserRouter>
<div className="App">
<button onClick={()=>setState('about')}>About</button>
<button onClick={()=>setState('profile')}>Profile</button>
<Routes>
<Route element={<About />} path='/about'></Route>
</Routes>
</div>
</BrowserRouter>
)
}
export default App;
Put the path before the component将路径放在组件之前
<Route path='/about' element={About}></Route>
Also ,还 ,
Wrap your in the index.js file with BrowserRouter
用BrowserRouter
将你的 index.js 文件包裹起来
<BrowserRouter>
<App/>
</BrowserRouter>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.