【发布时间】:2021-12-15 00:01:15
【问题描述】:
我有一个组件链接到我正在使用 getServerSideProps 的 NextJS 页面,并且需要访问参数和查询字符串。
我真的很想有一个“干净”的网址,例如“domain.com/usersname/likes”,最后没有“?userId=h337dhdh37dhdhd”。可以这样吗?
<Link href={`/${user?.username}/likes?userId=${id}`} as={`/${user?.username}/likes`}>
...
</Link>
在我的 getServerSideProps 中,我根据 Next 文档使用上下文:
export async function getServerSideProps(context) {
const username = context.params.username;
const userId = context.query.userId;
...
}
参数(用户名)很好,但无论我做什么,userId 始终是未定义的。谁能看看我做错了什么?
编辑:codesandbox 链接:https://codesandbox.io/s/nifty-bush-livm7 - 基于 Restricted Beam 下面的回答
非常感谢任何帮助,马特
【问题讨论】:
-
我无法重现该问题。您确定将
id变量传递给/${user?.username}/likes?userId=${id}时设置了吗? -
嗨 Julio,是的,作为测试,我设置了一个 const id = 'sampleId';但是当我记录它时它仍然出现未定义
-
这很奇怪。您能否提供一个可以重现问题的代码框(或类似内容)?
-
当然,我刚刚编辑了问题以添加链接
-
那个codeandbox链接似乎对我不起作用。