首页 > 解决方案 > 升级到 Gatsby v.2 后组件没有在 React 中呈现,即使我在 Gatsby CLI 中没有错误

问题描述

当我运行时,gatsby develop我没有收到任何错误,并且页面显示除了导航之外的所有内容。在 Chrome 开发工具中,我收到此错误:Warning: Each child in a list should have a unique "key" prop. 问题是我无法将此错误消息与我遇到的问题放在一起。

src/layouts/index.js

import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'

import Header from '../components/Header'

const Layout = ({ children, data }) => (
  <div>
    <Helmet
      title={data.site.siteMetadata.title}
      meta={[
        { name: 'description', content: data.site.siteMetadata.description },
        { name: 'keywords', content: data.site.siteMetadata.keywords },
      ]}
    />
    <Header />
    {children()}
  </div>
)

Layout.propTypes = {
  children: PropTypes.func,
}

export default Layout

export const query = graphql`
  query SiteTitleQuery {
    site {
      siteMetadata {
        title
        description
        keywords
      }
    }
  }
`

src/components/Header.js

import React from 'react'
import Link from 'gatsby-link'
import './Header.css'

class Header extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      hasScrolled: false
    }
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }

  handleScroll = (event) => {
    const scrollTop = window.pageYOffset

    if (scrollTop > 50) {
      this.setState({ hasScrolled: true })
    } else {
      this.setState({ hasScrolled: false })
    }
  }

  render() {
    return (
      <div className={this.state.hasScrolled ? 'Header HeaderScrolled' : 'Header'}>
        <div className="HeaderGroup">
          <Link to="/"><img src={require('../images/logo-designcode.svg')} width="30" /></Link>
          <Link to="/courses">Courses</Link>
          <Link to="/downloads">Downloads</Link>
          <Link to="/workshops">Workshops</Link>
          <Link to="/buy"><button>Buy</button></Link>
        </div>
      </div>
    )
  }
}

export default Header

这是我的gatsby info

System:
    OS: macOS 10.15.6
    CPU: (8) x64 Intel(R) Core(TM) i7-3615QM CPU @ 2.30GHz
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 12.16.2 - /usr/local/bin/node
    npm: 6.14.4 - /usr/local/bin/npm
  Languages:
    Python: 2.7.16 - /usr/bin/python
  Browsers:
    Chrome: 85.0.4183.102
    Safari: 13.1.2
  npmPackages:
    gatsby: ^2.24.55 => 2.24.56
    gatsby-link: ^2.4.13 => 2.4.13 => 2.4.13
    gatsby-plugin-react-helmet: ^3.3.10 => 3.3.10
    gatsby-plugin-styled-components: ^3.3.10 => 3.3.10
    gatsby-source-contentful: ^2.3.42 => 2.3.44
  npmGlobalPackages:
    gatsby-cli: 2.12.95

标签: reactjsgatsby

解决方案


There is no error, it is a warning as it is shown in the message. It doesn't block your rendering even it appears. This is a common warning that shows up in every loop that misses a key value in any React component. The key value must be unique and the purpose of using it is to help React to identify internally which items have changed (by adding/removing/re-ordering them). This article may help you to clarify some stuff.

For example:

{anyArray.map((item, index)=> <li key={item.value}>{item.value}</li>}

In the dummy example above, the key value is item.value. It's not recommended to use the index loop itself, however, you can append it to item.value if you want in order to avoid duplicated entries.

In addition, what I've found potentially code-breaking in your code is the usage of window without doing any validation before. As you can see in Gatsby's documentation about global objects (debugging builds), since the code is compiled in the server, the usage of global objects such as document or window may break the code because they are not defined at the time your code is requesting it. To fix this, just add:

  componentDidMount() {
    if(typeof window !== 'undefined'){
        window.addEventListener('scroll', this.handleScroll)
    }
  }

推荐阅读