React组件在使用Router、Routes、Route时不渲染



我正在学习React,我正在被介绍到React路由器DOM。我的问题是,我的组件没有渲染在React应用程序。

下面是我的代码:
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;

下面是Home和Login组件的代码:

const Home = () => {
return (
<div>Home</div>
)
}
export default Home;
const Login = () => {
return (
<div>Login</div>
)
}
export default Login;

我已经尝试重新安装react-router-dom,并尝试使用BrowerRouter代替,但仍然无济于事。此外,组件渲染不使用路由器或路由,但当我使用路由它中断。此外,我在控制台中收到了这个警告消息。

react.development.js:209警告:无效的钩子调用。钩子只能在函数组件的内部调用。这可能是由于以下原因之一:

  1. 你可能有不匹配的版本的React和渲染器(如React DOM)
  2. 你可能违反了Hooks的规则
  3. 你可能在同一个应用程序中有多个React副本有关如何调试和修复此问题的提示,请参阅https://reactjs.org/link/invalid-hook-call。
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.

您正在使用低级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;
}

只需使用一个高级路由器,即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>

);
}

相关内容

最新更新