Гэтсби-реактивный-шлем генерирует пустую <title>в SSR - PullRequest
2 голосов
/ 26 апреля 2020

Мой сайт 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" />

Ответы [ 2 ]

0 голосов
/ 27 апреля 2020

Нашел решение. Это проблема с redux-persist-store, из-за которой SSR не работал.

Полное решение можно найти в другом вопросе здесь: Гэтсби не генерирует правильные данные c HTML файлы

0 голосов
/ 26 апреля 2020

Можете ли вы попробовать что-то вроде title = {title}, передавая его как реквизит шлема, а не как тег заголовка, как у вас выше

  <Helmet
      htmlAttributes={{
        lang,
      }}
      title={title}
      titleTemplate={`%s | ${site.siteMetadata.title}`}
      meta={[
        {
          name: `description`,
          content: metaDescription,
        },
        {
          property: `og:title`,
          content: title,
        },
        {
          property: `og:description`,
          content: metaDescription,
        },
        {
          property: `og:type`,
          content: `website`,
        },
        {
          name: `twitter:card`,
          content: `summary`,
        },
        {
          name: `twitter:creator`,
          content: site.siteMetadata.author,
        },
        {
          name: `twitter:title`,
          content: title,
        },
        {
          name: `twitter:description`,
          content: metaDescription,
        },
      ].concat(meta)}
    />

Шаблон Gatsby Starter Default имеет хороший SEO-компонент Вы также можете ссылаться.

...