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

Next.js:如何通过Link组件在getServerSideProps中同时获取params与查询字符串并解决userId未定义问题

问题原因

你遇到的核心问题是**as属性只是用来美化客户端显示的URL,服务器端接收到的请求是美化后的URL(也就是/${user?.username}/likes),根本没有userId这个查询参数**,所以context.query.userId自然是undefined。

简单来说,as就像是给URL“戴了个面具”,浏览器地址栏看起来是简洁的,但服务器只认这个“面具”URL,不知道你原来href里藏的?userId=${id}。

解决方案

这里给你两个更合理的方案,比原来的写法更符合Next.js的路由逻辑:

方案1:把userId也加入路由参数(推荐)

调整你的页面路由结构,比如创建pages/[username]/[userId]/likes.js,这样URL就变成domain.com/{username}/{userId}/likes,完全符合你想要的简洁格式。

然后在getServerSideProps里直接从params获取两个值:

export async function getServerSideProps(context) {
  const { username, userId } = context.params;
  // 接下来用这两个参数做你需要的操作
  return {
    props: { username, userId }
  };
}

对应的Link写法也更简洁:

<Link href={`/${user?.username}/${id}/likes`}>
  ...
</Link>

方案2:通过username获取userId(更安全)

既然username是唯一的,你完全可以在服务器端通过username去数据库/后端接口查询对应的userId,不需要在URL里传递userId,这样既简洁又避免暴露用户ID。

代码示例:

export async function getServerSideProps(context) {
  const { username } = context.params;
  
  // 假设你有一个通过用户名获取用户信息的方法
  const user = await fetchUserByUsername(username);
  
  // 如果用户不存在,返回404
  if (!user) {
    return { notFound: true };
  }
  
  const userId = user.id;
  // 接下来用userId处理业务逻辑
  return {
    props: { user, userId }
  };
}

对应的Link写法也不需要多余的query参数了:

<Link href={`/${user?.username}/likes`}>
  ...
</Link>
为什么原来的写法行不通?

再强调一下:as属性只是客户端的URL美化,服务器端不会解析你href里的原始查询参数。当用户直接访问这个美化后的URL,或者页面在服务器端渲染时,服务器只能拿到/${username}/likes这个路径,没有userId的信息,所以自然拿不到值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:19:07