【问题标题】:Using a static query in a React class component在 React 类组件中使用静态查询
【发布时间】:2021-06-26 22:33:43
【问题描述】:

我尝试在 Gatsby 的 react 类组件中使用静态查询。

import * as React from "react"
    import '../styles/layout.scss'
    import Layout from '../components/layout'
    import { useStaticQuery, graphql } from 'gatsby'
    import { container } from '../styles/mystyles.module.scss'
    class IndexPage extends React.Component {
        constructor(props) {
            super(props);
        }
        render() {
           return  <Layout>
                <div>
                    <h1 className={container}>hello </h1>
                    <div>This is my container</div>
                </div>
            </Layout>
        }
    }
    const data = useStaticQuery(graphql`
        query HeaderQuery {
          site {
            siteMetadata {
              title
            }
          }
        }
      `)
    
    export default IndexPage

我得到了错误

19:14 错误 React Hook "useStaticQuery" 不能在顶层调用。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数 react-hooks/rules-of-hooks 中调用

这是否意味着它不可能,它必须是一个功能组件?

【问题讨论】:

    标签: reactjs components gatsby


    【解决方案1】:

    问题在于您尝试在“顶层”(函数外)调用函数,而挂钩仅在从函数组件内部调用时才起作用。例如:

    const YourComponent = () => {
      const data = useStaticQuery(yourQuery)
    }
    

    如果你不想使用函数组件,你仍然可以使用StaticQuery高阶组件来代替:

    export default (props) => 
      <StaticQuery query={yourQuery}>
        {({ data }) => <SomeComponent {...data} {...props} />}
      </StaticQuery>
    

    ……或者像这样……

    class SomeComponent extends React.Component {
      render() {
        return (
          <StaticQuery query={yourQuery}>
            {({ data }) => <div>{data.site.title}</div>}
          </StaticQuery>
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2019-06-12
      • 2019-09-10
      • 1970-01-01
      • 2020-08-31
      • 2015-02-12
      相关资源
      最近更新 更多