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

NextJS 13中如何在getServerSideProps里使用resolvedUrl获取pathname?

在服务端渲染组件中获取pathname(无需客户端渲染)

直接在页面级组件中使用getServerSideProps即可在服务端获取pathname,且能保持组件的服务端渲染状态,具体实现如下:

  1. 在页面组件中导出getServerSideProps函数,从函数的context参数中提取pathname
  2. 将pathname作为props传递给页面组件,组件内部直接使用该props即可

代码示例

function HomePage({ pathname }) {
  // 直接使用服务端传递的pathname,组件保持服务端渲染
  return <h1>当前页面路径:{pathname}</h1>;
}

// 该函数在服务端执行,不会触发客户端渲染
export async function getServerSideProps(context) {
  // 从context中获取当前页面的pathname(不含查询参数)
  const { pathname } = context;
  
  // 如果需要包含查询参数的完整路径,可使用context.asPath
  // const { asPath } = context;

  return {
    props: {
      pathname,
      // asPath
    },
  };
}

export default HomePage;

子组件中使用pathname的方式

如果子组件需要pathname,直接通过props从页面组件传递即可,无需使用客户端钩子:

// 子组件
function Breadcrumb({ currentPath }) {
  return <div>当前位置:{currentPath}</div>;
}

// 页面组件
function ProductPage({ pathname }) {
  return (
    <div>
      <h1>商品详情页</h1>
      <Breadcrumb currentPath={pathname} />
    </div>
  );
}

export async function getServerSideProps(context) {
  const { pathname } = context;
  return { props: { pathname } };
}

export default ProductPage;

关键说明

  • getServerSideProps是Next.js提供的服务端数据获取方法,每次请求都会在服务端执行,完全不会触发客户端渲染
  • context.pathname返回当前页面的路由路径(不含查询参数),context.asPath返回包含查询参数的完整路径
  • 这种方式获取的pathname在服务端生成,组件渲染时直接使用,不会像usePathname那样强制组件转为客户端渲染

内容的提问来源于stack exchange,提问作者Víctor Manuel Nevárez Herrera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:06:29