【发布时间】:2020-04-27 18:11:58
【问题描述】:
我的 Gatsby 网站没有在 SSR 上生成正确的标题标签。当我建立网站时,我在生成的文件上得到的所有文件都是<title data-react-helmet="true"></title>。我很感激能帮助您找到问题并解决,因为经过长时间的调试过程后,我不知道可能是哪个问题。
相关文件:
package.json
...
"dependencies": {
"gatsby": "^2.19.45",
"gatsby-image": "^2.2.44",
"gatsby-plugin-manifest": "^2.2.48",
"gatsby-plugin-react-helmet": "^3.2.2",
"gatsby-plugin-sharp": "^2.4.13",
"gatsby-plugin-sitemap": "^2.3.1",
"gatsby-plugin-typescript": "^2.3.3",
"gatsby-source-filesystem": "^2.1.56",
"gatsby-source-graphql": "^2.2.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-helmet": "^6.0.0",
}
...
gatsby.config.js
plugins: [
`gatsby-plugin-react-helmet`,
...
]
(gatsby-plugin-offline 已禁用)
Seo.tsx
import React from "react"
import { Helmet } from "react-helmet"
import { useStaticQuery, graphql } from "gatsby"
interface Props {
title: string
description?: string
image?: string
}
const SEO = ({ title, description, image }: Props) => {
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata {
title
description
image
siteUrl
}
}
}
`
)
const metaDescription = description || site.siteMetadata.description
const shareImage = image || site.siteMetadata.image
const url = site.siteMetadata.siteUrl
return (
<Helmet defer={false}>
<title>{title}</title>
<meta name="description" content={metaDescription} />
<meta name="image" content={shareImage} />
<link rel="canonical" href={url} />
<meta property="og:url" content={url} />
<meta property="og:type" content="website" />
<meta property="og:title" content={title} />
<meta property="og:description" content={metaDescription} />
<meta property="og:image" content={shareImage} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={metaDescription} />
<meta name="twitter:image" content={shareImage} />
</Helmet>
)
}
export default SEO
将<title>{title}</title> 更改为<Helmet title={title}> 或删除defer={true} 不会改变结果中的任何内容。
gatsby-ssr.js
import React from "react"
import { Helmet } from "react-helmet"
export const onRenderBody = (
{ setHeadComponents, setHtmlAttributes, setBodyAttributes },
pluginOptions
) => {
const helmet = Helmet.renderStatic()
setHtmlAttributes(helmet.htmlAttributes.toComponent())
setBodyAttributes(helmet.bodyAttributes.toComponent())
setHeadComponents([
helmet.title.toComponent(),
helmet.link.toComponent(),
helmet.meta.toComponent(),
helmet.noscript.toComponent(),
helmet.script.toComponent(),
helmet.style.toComponent()
])
}
我仍然有一个空的 srr 文件的问题。
在任何给定的页面上,我都会调用 SEO 标签,例如:
<SEO title="Hello World" description="Foo Bar" />
【问题讨论】:
标签: javascript reactjs gatsby server-side-rendering react-helmet