React Router 导航栏出现两次(V6)
React Router navbar appears twice (V6)
导航栏在页面顶部和底部不断出现两次。当我检查页面时,元素显示 App 出现了两次并复制了导航。
App.js:
import {Outlet} from "react-router-dom";
import './App.css';
import Nav from "./components/Nav";
function App() {
return (
<div className="App">
<Nav/>
<Outlet/>
</div>
);
}
export default App;
nav.js:
import {Link} from "react-router-dom";
function Nav(){
return(
<nav>
<Link to ={"/"}>Home </Link>
<Link to ={"/data"}>Data </Link>
<Link to ={"/cool"}>Cool </Link>
</nav>
)
}
export default Nav;
问题
您正在渲染 App
组件两次。
index.js
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path={"/"} element={<App/>}> // <-- here as a layout component
<Route index element={<Home/>}/>
<Route path={"Box1"} element={<Box1/>}/>
<Route path={"Box2"} element={<Box2/>}/>
<Route path={"Box3"} element={<Box3/>}/>
<Route path={"data"} element={<Data/>}>
<Route index element={<Object/>}/>
<Route path={"/data/:id"} element={<User/>}/>
</Route>
<Route path={"cool"} element={<Cool/>}/>
</Route>
</Routes>
<App /> // <-- and again here by itself
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
解决方案
删除未呈现为路由布局组件的第二个 App
组件。
导航栏在页面顶部和底部不断出现两次。当我检查页面时,元素显示 App 出现了两次并复制了导航。
App.js:
import {Outlet} from "react-router-dom";
import './App.css';
import Nav from "./components/Nav";
function App() {
return (
<div className="App">
<Nav/>
<Outlet/>
</div>
);
}
export default App;
nav.js:
import {Link} from "react-router-dom";
function Nav(){
return(
<nav>
<Link to ={"/"}>Home </Link>
<Link to ={"/data"}>Data </Link>
<Link to ={"/cool"}>Cool </Link>
</nav>
)
}
export default Nav;
问题
您正在渲染 App
组件两次。
index.js
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path={"/"} element={<App/>}> // <-- here as a layout component
<Route index element={<Home/>}/>
<Route path={"Box1"} element={<Box1/>}/>
<Route path={"Box2"} element={<Box2/>}/>
<Route path={"Box3"} element={<Box3/>}/>
<Route path={"data"} element={<Data/>}>
<Route index element={<Object/>}/>
<Route path={"/data/:id"} element={<User/>}/>
</Route>
<Route path={"cool"} element={<Cool/>}/>
</Route>
</Routes>
<App /> // <-- and again here by itself
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
解决方案
删除未呈现为路由布局组件的第二个 App
组件。