【问题标题】:Error while using Location prop in Gatsby Helmet在盖茨比头盔中使用位置道具时出错
【发布时间】:2021-08-18 02:27:19
【问题描述】:

我想在包含路径名的 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

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

有没有更好的方法来为每个页面添加唯一的类或 ID?

【问题讨论】:

  • 你是从父级传递历史对象吗?还是您正在浏览 &lt;Link/&gt; ?如果您使用&lt;Link/&gt;,那么我相信您已经配置BrowserRouter 来导航到SEO 组件?请澄清。

标签: reactjs location gatsby react-props react-helmet


【解决方案1】:

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

location 属性被传递给任何页面组件并表示 应用程序当前所在的位置,您希望它去哪里,以及其他 有用的信息。

因此,要在 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" }) => {}

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-01-22
    • 1970-01-01
    • 2021-02-13
    • 2022-08-15
    • 2020-02-20
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多