reactjs 如何防止切换路由后页面重载

pokxtpni  于 2022-11-04  发布在  React
关注(0)|答案(2)|浏览(185)

我的侧边栏使用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 /}/〉,但这导致侧边栏完全消失。

qyyhg6bp

qyyhg6bp1#

您应该使用Link组件,而不是更改window.location.pathname

{SideNav_Data.map((val, key) => {
    return (
        <Link 
            key={key} 
            className = "row"
            id={window.location.pathname === val.link ? "active" : ""}
            to={val.link}
        >
            <div id='icon'>{val.icon}</div>{" "}<div id='title'>{val.title}</div>
        </Link>
    )
})}
ee7vknir

ee7vknir2#

个问题

  • 使用window.location.pathname设置当前URL路径将必然触发页面重新加载并重新装载整个应用程序。请使用从react-router-dom导出的链接组件之一在应用程序中发出声明性导航操作。
  • SideNav组件消失,因为只有在路径为"/"时呈现Home组件时才会呈现该组件。请使用布局路径来呈现SideNav组件

溶液

我建议导入并使用NavLink组件,因为它是Link组件的一个特殊版本,默认情况下应用"active"类名。如果需要计算li元素的id属性,则使用useLocation钩子访问当前的location.pathname值。
示例:

import { NavLink, useLocation } from 'react-router-dom';

...

function SideNav() {
  const { pathname } = useLocation();

  return (
    <div className="SideNav">
      <img src={Sunrise} className='SideNavImg' alt='' />
      <ul className="SideNavList">
        {SideNav_Data.map((val) => (
          <li
            key={val.link} 
            className="row"
            id={pathname === val.link ? "active" : ""}
          >
            <NavLink to={val.link} end>
              <div id='icon'>{val.icon}</div>
              {" "}
              <div id='title'>{val.title}</div>
            </NavLink>
          </li>
        ))}
      </ul>
    </div>
  );
}

SideNav作为布局路线的一部分进行渲染,以便使用您希望渲染的路线有条件地渲染它。
示例:

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Outlet,
} 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';
import SideNav from './Components/SideNav';

const SideNavLayout = () => (
  <>
    <SideNav />
    <Outlet />
  </>
);

function App() {
  return (
    <Router>
      <Routes>
        <Route element={<SidNavLayout />}>
          <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 />} />
        </Route>
      </Routes>
    </Router>
  );
}

首页

import React from 'react';

function Home() {
  return (
    <div>
      ...
    </div>
  );
}

export default Home;

相关问题