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

如何在React Router v6的App.js中实现导航+首页欢迎消息自动隐藏

React Router v6 首页欢迎消息按需显示方案

问题描述

跟随《React Router v6教程》完成项目后,发现App.js仅作为导航栏存在,首页无内容。希望在App.js中添加欢迎消息:Welcome to my application! Use the navigation above.,且点击导航栏链接后该消息自动消失。目前点击链接后消息会显示在其他内容上方,由于App.js是路由的父组件导致此问题。已知拆分导航为独立组件、设置平级路由的解决方法,但希望保留教程的路由结构。

核心代码

index.js

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <BrowserRouter basename="/raston-router">
        <Routes>
          <Route path="/" element={<App />}>
            <Route path="output" element={<Output />} />
            <Route path="input" element={<Input />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </Provider>
  </React.StrictMode>
);

App.js

export default function App() {
  return (
    <div>
      <h1>Raston Router and Redux</h1>
      <nav style={{ borderBottom: "solid 1px", paddingBottom: "1rem" }}>
        <Link to="/input" style={{ padding: "10px" }}>
          Input
        </Link>
        <Link to="/output" style={{ padding: "10px" }}>
          Output
        </Link>
      </nav>
      // welcome message would go here
      <Outlet />
    </div>
  );
}

解决方案

利用React Router v6的useLocation钩子,判断当前路由路径是否为根路径/,仅在根路径时渲染欢迎消息,具体修改如下:

  1. 导入useLocation钩子:
import { Link, Outlet, useLocation } from 'react-router-dom';
  1. 在App组件中获取当前路径并判断:
export default function App() {
  const location = useLocation();
  const isRootPath = location.pathname === '/';

  return (
    <div>
      <h1>Raston Router and Redux</h1>
      <nav style={{ borderBottom: "solid 1px", paddingBottom: "1rem" }}>
        <Link to="/input" style={{ padding: "10px" }}>
          Input
        </Link>
        <Link to="/output" style={{ padding: "10px" }}>
          Output
        </Link>
      </nav>
      {isRootPath && (
        <p>Welcome to my application! Use the navigation above.</p>
      )}
      <Outlet />
    </div>
  );
}

这样修改后,只有在访问首页(根路径)时才会显示欢迎消息,点击导航跳转到/input或/output时,消息会自动隐藏,同时保留了原有的嵌套路由结构,无需拆分导航组件或调整路由层级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:21:24