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

Next.js中使用useRouter传递props问题:标题组件无内容显示

问题排查与修复方案

一、Title组件语法错误

你的Title组件存在两处致命语法问题,直接导致内容无法显示:

  • 多嵌套了一层大括号,JSX中表达式仅需一层{}包裹
  • 括号不匹配,缺少闭合的}
  • 逻辑写反:当前代码仅在根路径/时显示标题,与你"根据子URL显示标题"的需求完全相反

错误代码:

return <div>{{router.pathname === "/" ? title : ""}</div>;

修复后(以非根路径显示标题为例):

return <div>{router.pathname !== "/" ? title : ""}</div>;

二、侧边栏与Header无状态共享

Sidebar里的activeIcon是组件内部局部状态,Header组件无法获取该值,导致传递给Title的title props始终为空或未正确赋值。

解决方法:状态提升到共同父组件

把标题状态提升到Sidebar和Header的共同父组件(如_app.js或页面级组件),通过props传递给两个组件:

  1. 父组件示例:
import { useState } from 'react';
import Sidebar from './sidebar';
import Header from './header';

const Layout = ({ children }) => {
  const [activeTitle, setActiveTitle] = useState("");

  return (
    <div className="layout">
      <Sidebar setActiveTitle={setActiveTitle} />
      <div className="main-content">
        <Header title={activeTitle} />
        {children}
      </div>
    </div>
  );
};

export default Layout;
  1. 修改Sidebar接收父组件的状态更新方法:
import { navItems } from "../../static/NavItems";
import { useEffect } from 'react';

const Sidebar = ({ setActiveTitle }) => {
  const router = useRouter();

  // 初始化时根据当前路由自动匹配标题
  useEffect(() => {
    const currentNav = navItems.find(item => router.pathname === item.path);
    if (currentNav) setActiveTitle(currentNav.title);
  }, [router.pathname, setActiveTitle]);

  return (
    <Wrapper>
      <LogoContainer>
        <Logo>
          <Image src={logo} alt="Logo" width={200} />
        </Logo>
      </LogoContainer>
      <NavItemsContainer>
        {navItems.map((nav, i) => (
          <NavItem 
            key={i} 
            onClick={() => setActiveTitle(nav.title)}
            className={router.pathname === nav.path ? "active" : ""}
          >
            <NavIcon style={{ color: router.pathname === nav.path ? "#3773f5" : "" }}>
              {nav.icon}
            </NavIcon>
            <NavTitle>
              <Link as={nav.as} href={nav.path}>
                {nav.title}
              </Link>
            </NavTitle>
          </NavItem>
        ))}
      </NavItemsContainer>
    </Wrapper>
  );
};

三、更简洁的替代方案:直接在Title组件匹配路由

无需组件间传递状态,直接在Title组件中根据当前路由从navItems匹配对应标题,避免状态不同步问题:

import { useRouter } from "next/router";
import { navItems } from "../static/NavItems";

const Title = () => {
  const router = useRouter();
  const currentNav = navItems.find(item => router.pathname === item.path);
  const currentTitle = currentNav ? currentNav.title : "默认标题";

  return <div>{currentTitle}</div>;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:01:41