You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React路由跳转后隐藏指定组件?useState方案失效求助

解决方案

原始代码

import {Routes, Route} from 'react-router-dom';
import HomePage from './Pages/Home';
import AboutPage from './Pages/About';
import ServicesPage from './Pages/Services';
import Meet from './Components/Meet';
import NavBar from './Components/layout/NavBar';
function App() {
  return (
    <div className="App">
        <Meet text='my meet up'/>
        <Meet text='my name'/>
        <Meet text='contact information'/>
        <NavBar/>
        <Routes>
          <Route path='/home' element={<HomePage/>}/>
          <Route path='/about' element={<AboutPage/>}/>
          <Route path='/service' element={<ServicesPage/>}/>
        </Routes>
    </div>
  );
}

export default App;

需求说明

点击任意路由链接时,隐藏<Meet text='my meet up' />组件,仅显示对应路由的页面内容。

可行方案

使用react-router-dom的useLocation钩子监听当前路由路径,通过路径判断控制组件显示:

import {Routes, Route, useLocation} from 'react-router-dom'; // 导入useLocation
import HomePage from './Pages/Home';
import AboutPage from './Pages/About';
import ServicesPage from './Pages/Services';
import Meet from './Components/Meet';
import NavBar from './Components/layout/NavBar';

function App() {
  const location = useLocation();
  // 定义需要隐藏目标组件的路由路径
  const targetPaths = ['/home', '/about', '/service'];
  // 判断当前路径是否在目标列表中
  const hideMeetUp = targetPaths.includes(location.pathname);

  return (
    <div className="App">
        {/* 条件渲染:不在指定路由时才显示该Meet组件 */}
        {!hideMeetUp && <Meet text='my meet up'/>}
        <Meet text='my name'/>
        <Meet text='contact information'/>
        <NavBar/>
        <Routes>
          <Route path='/home' element={<HomePage/>}/>
          <Route path='/about' element={<AboutPage/>}/>
          <Route path='/service' element={<ServicesPage/>}/>
        </Routes>
    </div>
  );
}

export default App;

原理说明

  1. useLocation钩子:获取当前路由的位置对象,其中pathname属性对应当前页面路径(如/home)。
  2. 条件渲染:通过判断当前路径是否在预设的路由列表中,决定是否渲染<Meet text='my meet up' />。当用户点击路由链接跳转后,路径匹配,该组件自动隐藏。

内容的提问来源于stack exchange,提问作者Benj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:22:45