我的侧边栏使用react-router-dom通过路由在页面文件之间切换,但是当我切换路由时,我的页面会重新加载。有没有方法可以在不重新加载页面的情况下切换路由?
提要字段
import React from 'react'
import {SideNav_Data} from "./SideNav_Data"
import Sunrise from './Sunrise.png'
function SideNav() {
return (
<div className = "SideNav">
<img src={Sunrise} className='SideNavImg' alt=''/>
<ul className="SideNavList">
{SideNav_Data.map((val, key) => {
return (
<li key={key}
className = "row"
id={window.location.pathname === val.link ? "active" : ""}
onClick = {() => {
window.location.pathname = val.link;
}}>
<div id='icon'>{val.icon}</div>{" "}<div id='title'>{val.title}</div>
</li>
)
})}
</ul>
</div>
)
}
export default SideNav
边栏数据
import React from 'react'
import CottageIcon from '@mui/icons-material/Cottage';
import DirectionsCarFilledIcon from '@mui/icons-material/DirectionsCarFilled';
import PersonIcon from '@mui/icons-material/Person';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import ContactSupportIcon from '@mui/icons-material/ContactSupport';
export const SideNav_Data = [
{
title: "Home",
icon: <CottageIcon />,
link: "/"
},
{
title: "Cars",
icon: <DirectionsCarFilledIcon />,
link: "/Cars"
},
{
title: "Representatives",
icon: <PersonIcon />,
link: "/Representatives"
},
{
title: "Loan Estimator",
icon: <AccountBalanceIcon />,
link: "/Loan-Estimator"
},
{
title: "Account",
icon: <AccountCircleIcon />,
link: "/Account"
},
{
title: "Support",
icon: <ContactSupportIcon />,
link: "/Support"
},
]
首页
import React from 'react'
import SideNav from '../Components/SideNav'
function Home() {
return (<div>
<SideNav />
</div>
)
}
export default Home
App.js
import './App.css';
import { BrowserRouter as Router, Routes, Route} from "react-router-dom"
import Home from './Pages/Home';
import Cars from './Pages/Cars';
import Reps from './Pages/Reps';
import LoanEst from './Pages/LoanEst';
import Account from './Pages/Account';
import Support from './Pages/Support';
function App() {
return (
<Router>
<Routes>
<Route path='/' element={<Home />}/>
<Route path="/Cars" element={<Cars />}/>
<Route path="/Representatives" element={<Reps />}/>
<Route path="/Loan-Estimator" element={<LoanEst />}/>
<Route path="/Account" element={<Account />}/>
<Route path="/Support" element={<Support />}/>
</Routes>
</Router>
)
}
export default App;
我试过切换“链接:“部分侧边栏数据到〈Link to={Home /}/〉,但这导致侧边栏完全消失。
2条答案
按热度按时间qyyhg6bp1#
您应该使用
Link
组件,而不是更改window.location.pathname
:ee7vknir2#
个问题
window.location.pathname
设置当前URL路径将必然触发页面重新加载并重新装载整个应用程序。请使用从react-router-dom
导出的链接组件之一在应用程序中发出声明性导航操作。SideNav
组件消失,因为只有在路径为"/"
时呈现Home
组件时才会呈现该组件。请使用布局路径来呈现SideNav
组件溶液
我建议导入并使用
NavLink
组件,因为它是Link
组件的一个特殊版本,默认情况下应用"active"
类名。如果需要计算li
元素的id
属性,则使用useLocation
钩子访问当前的location.pathname
值。示例:
将
SideNav
作为布局路线的一部分进行渲染,以便使用您希望渲染的路线有条件地渲染它。示例:
首页