在 Gatsby 头盔中使用 Location 道具时出错

Error while using Location prop in Gatsby Helmet

我想将 class 添加到包含路径名的 body 标签。 我想我应该可以访问 location 道具并且我应该能够通过它。 但是位置被传递为空。

我将其用作资源:https://www.gatsbyjs.com/docs/location-data-from-props/

/**
 * SEO component that queries for data with
 *  Gatsby's useStaticQuery React hook
 *
 * See: https://www.gatsbyjs.org/docs/use-static-query/
 */

import React from "react"
import PropTypes from "prop-types"
import Helmet from "react-helmet"
import { useStaticQuery, graphql } from "gatsby"

const SEO = ({ description, lang, meta, title, location }) => {
  const mylocation = location.pathname;
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
            description
          }
        }
      }
    `
  )

  const metaDescription = description || site.siteMetadata.description

  return (
    <Helmet
      htmlAttributes={{
        lang,
      }}
      title= "Hello"
      titleTemplate={'%s | ${site.siteMetadata.title}'}
      meta={[
        {
          name: 'description',
          content: metaDescription,
        },
        {
          property: 'og:title',
          content: mylocation,
        },
        {
          property: 'og:description',
          content: metaDescription,
        },
        {
          property: 'og:type',
          content: 'website',
        },
      ].concat(meta)}
    >
    <body className={mylocation} />
  </Helmet>
  )
}

SEO.defaultProps = {
  lang: 'en',
  meta: [],
  description: '',
}

SEO.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.arrayOf(PropTypes.object),
  title: PropTypes.string.isRequired,
  location: PropTypes.string,
}

export default SEO

渲染此页面时-> http://localhost:8000/about/ 我希望看到 mylocation = /about

相反,我看到了

Error in function SEO in ./src/components/seo.js:14
Cannot read property 'pathname' of undefined

./src/components/seo.js:14

为什么我的位置属性未定义?

是否有更好的方法为每个页面添加唯一的 class 或 ID?

location 是顶级 属性 因此它仅在页面组件中可用,如您在 docs:

中所见

the location prop is passed to any page component and represents where the app is currently, where you’d like it to go, and other helpful information.

因此,要在 SEO 组件中使用它,您需要将其从任何页面组件中提取出来,例如:

const AboutMePage = ({ location, otherProps }) => {

    return <Layout>
      <SEO location={location} 
           description={`Some description`}
           lang={`Some lang`}
           meta={`Some meta`}
           title={`Some title`} />
       ...
    </Layout>

}

其余页面依此类推。

如果你想避免代码中断,你可以使用默认值,以防你错过传递 props 的情况,例如:

const SEO = ({ description, lang, meta, title, location="some default value" }) => {}