[英]React Components not rendering when using Router, Routes, Route
I'm learning React and I'm being introduced to React Router DOM.我正在学习 React,我正在学习 React Router DOM。 My issue is that my components aren't rendering in the React App.我的问题是我的组件没有在 React App 中呈现。
Here is my code:这是我的代码:
import Home from "./pages/main/Home";
import Login from "./pages/login/Login";
import {Router, Routes, Route} from "react-router-dom";
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
</Routes>
</Router>
</div>
);
}
export default App;
Here is the code for the Home and Login Components:这是主页和登录组件的代码:
const Home = () => {
return (
<div>Home</div>
)
}
export default Home;
const Login = () => {
return (
<div>Login</div>
)
}
export default Login;
I've tried to reinstall react-router-dom and tried using BrowerRouter instead but still no avail.我尝试重新安装 react-router-dom 并尝试改用 BrowerRouter 但仍然无济于事。 Also the components render without using Router or Routes but when I use Routes it breaks.此外,组件在不使用 Router 或 Routes 的情况下呈现,但是当我使用 Routes 时它会中断。 Furthermore, I received this warning message in the console.此外,我在控制台中收到了这条警告消息。
react.development.js:209 Warning: Invalid hook call. react.development.js:209 警告:无效的钩子调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的内部调用。 This could happen for one of the following reasons:这可能由于以下原因之一而发生:
The above error occurred in the <Router> component:
at Router (http://localhost:3000/main.2c5a7d71e5ac5c56f4c5.hot-update.js:4470:15)
at div
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
You are using the low-level Router
and not passing required props to it.您正在使用低级Router
并且没有将所需的道具传递给它。
declare function Router( props: RouterProps ): React.ReactElement | null; interface RouterProps { basename?: string; children?: React.ReactNode; location: Partial<Location> | string; // <-- required? navigationType:; NavigationType: navigator; Navigator? // <-- required: static;: boolean; }
Just use one of the high-level router, ie BrowswerRouter
, HashRouter
, etc.只需使用高级路由器之一,即BrowswerRouter
、 HashRouter
等。
import {
BrowserRouter as Router,
Routes,
Route
} from "react-router-dom";
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
</Routes>
</Router>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.