React路由器不渲染组件



我是新手,面对问题。如果我直接在app.js中添加它们,组件就会工作,但由于我使用路由,它不会渲染组件,所以直接组件渲染得很好。对于下面的代码,它呈现<Navbar /><Footer />,但不呈现其他组件。

import React from "react";
import Footer from "./components/Footer";
import Navbar from "./components/Navbar";
import Sad from "./components/Pages/Sad";
import World from "./components/Pages/World";
import Hero from "./components/Hero";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
function App() {
return (
<Router>
<div className="App">
<Navbar />
<Routes>
<Route path="/" component={Hero} />
<Route path="/sad" component={Sad} />
<Route path="/about" component={World} />
</Routes>
<Footer />
</div>
</Router>
);
}
export default App;

在最新的react版本中,你应该这样修改你的代码:

import React from "react";
import Footer from "./components/Footer";
import Navbar from "./components/Navbar";
import Sad from "./components/Pages/Sad";
import World from "./components/Pages/World";
import Hero from "./components/Hero";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
function App() {
return (
<div className="App">
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Hero />}/>
<Route path="/sad" element={<Sad/>} />
<Route path="/about" element={<World/>} />
</Routes>
<Footer />
</Router>
</div>

);
}
export default App;

https://reactrouter.com/docs/en/v6/getting-started/overview

相关内容

  • 没有找到相关文章

最新更新