在 next.js 中获取 url 查询参数时遇到问题 [英] Having trouble getting url query parameter in next.js
问题描述
我只是想在我的 url 中获取参数的值.
我是 next.js 的新手,但总体来说还是很陌生.
我的网址是这样的:
localhost:3000/?code=VhXHWwRemC32dPmm3oj0mMravO6MP3
现在,我只是在渲染一个像这样的页面:
const Index = () =>{常量路由器 = useRouter();常量代码 = router.query.code;控制台.log(代码);返回(<p>代码:{code}</p><a href={Oauth.discord_login_url}登录</a></div>)};只是为了让我看看我是否从 url 中正确获取了代码.
一旦我使用 discord 登录,我会返回到 Index,然后 url 看起来就像我在上面显示的那样.我正在尝试获取代码的价值,以便我可以使用它.让我困惑的是
<p>code: {code}</p>
成功在页面上显示code"的值.但是
console.log(code)
显示未定义.为什么不一样?
解决方案 尝试添加getInitialProps
:
const Index = () =>{常量路由器 = useRouter();常量代码 = router.query.code;控制台.log(代码);Index.getInitialProps = async() =>{返回 {};};返回 (<p>代码:{code}</p><a href={Oauth.discord_login_url}>登录</a></div>)};I am just trying to get the value of a parameter in my url.
I'm new to next.js and still fairly new to react in general.
My url looks like:
localhost:3000/?code=VhXHWwRemC32dPmm3oj0mMravO6MP3
Right now, I just am rendering a page like:
const Index = () => {
const router = useRouter();
const code = router.query.code;
console.log(code);
return(
<div>
<p>code: {code}</p>
<a href={Oauth.discord_login_url}login</a>
</div>)
};
Just so I can see if I'm getting the code correctly from the url.
Once I log in with discord, I return to Index and the url then looks like what I showed above. I am trying to get the value of code so I can use it. What confuses me is that
<p>code: {code}</p>
successfully displays the value of "code" on the page. But
console.log(code)
shows undefined. Why is it different?
解决方案 Try to add getInitialProps
:
const Index = () => {
const router = useRouter();
const code = router.query.code;
console.log(code);
Index.getInitialProps = async () => {
return {};
};
return (
<div>
<p>code: {code}</p>
<a href={Oauth.discord_login_url}>login</a>
</div>
)
};
这篇关于在 next.js 中获取 url 查询参数时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文