[英]How to get URL params when using Custom Document in NextJS
I am using NextJS to product SSR pages, and these pages are language-specific.我正在使用 NextJS 来制作 SSR 页面,这些页面是特定于语言的。 I would like to set the lang property to declare the language of the text.
我想设置 lang 属性来声明文本的语言。
So far I have:到目前为止,我有:
import Document, { Html, Head, Main, NextScript } from "next/document"
import Router from "next/router"
class MyDocument extends Document {
render() {
const { lanaguage } = Router.router.query
return (
<Html lang={language}>
<Head />
<body className="antialiased text-white text-base font-sans">
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
However, Router.router
is always null
when using a Custom Document ( _document.js
).但是,
Router.router
在使用自定义文档 ( _document.js
) 时始终为null
。 Is there another way to get the URL params/query when using a Custom Document?使用自定义文档时,还有其他方法可以获取 URL 参数/查询吗?
Since Next.js v10, if you're using the built-in i18n routing , Next will automatically set the lang
attribute of the document.从 Next.js v10 开始,如果你使用内置的i18n 路由,Next 会自动设置文档的
lang
属性。
From the documentation:从文档中:
Since Next.js knows what language the user is visiting it will automatically add the
lang
attribute to the<html>
tag.由于 Next.js 知道用户正在访问什么语言,它会自动将
lang
属性添加到<html>
标签。Next.js doesn't know about variants of a page so it's up to you to add the
hreflang
meta tags usingnext/head
.Next.js 不知道页面的变体,因此您可以使用
next/head
添加hreflang
元标记。 You can learn more abouthreflang
in the Google Webmasters documentation .您可以在Google 网站管理员文档中了解有关
hreflang
的更多信息。
I have been able to solve this by using:我已经能够通过使用来解决这个问题:
import Document, { Html, Head, Main, NextScript } from "next/document"
class MyDocument extends Document {
render() {
const { lanaguage } = this.props.__NEXT_DATA__.query
return (
<Html lang={lanaguage}>
<Head />
<body className="antialiased text-white text-base font-sans">
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
I am unsure if it is bad practice to use this.props.__NEXT_DATA__
.我不确定使用
this.props.__NEXT_DATA__
是否是不好的做法。 However, it does have the information I require.但是,它确实有我需要的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.