对来自Gatsby组件中插件的数据使用静态查询

时间:2019-02-06 17:24:01

标签: reactjs gatsby

我是React和Gatsby的新手。 我正在尝试从组件中的gatsby csv插件获取数据。 我读到在组件中,您必须使用静态查询来获取数据,但我无法使其正常工作。我收到“无法读取未定义的属性'props'”,因此我认为我在数据构造函数中做错了,或者语法是错误的。

import React from 'react';
import { StaticQuery, graphql } from "gatsby"

const data = this.props.data.allLettersCsv.edges

export default () => (
  <StaticQuery
    query={graphql`
      query Corrispondences {
        allLettersCsv {
          edges {
            node {
              word
              value
            }
          }
        }
      }
    `}
    render={data.map((row,i) => (
        <div>
        <table>
          <thead>
            <tr>
              <th>Letter</th>
              <th>ASCII Value</th>
            </tr>
          </thead>
          <tbody>
              <tr key={`${row.node.value} ${i}`}>
                <td>{row.node.word}</td>
                <td>{row.node.value}</td>
              </tr>
          </tbody>
        </table>
      </div>
      ))
    }
  />
)

1 个答案:

答案 0 :(得分:0)

您的代码中有2个问题:

首先,您要在组件外部声明数据:

json

模块范围中可能没有requests.patch,因此会出现错误。您应该删除此行,因为gatsby通过const data = this.props.data.allLettersCsv.edges 的{​​{1}}向您的组件提供了graphql查询结果。

第二,this.props的{​​{1}}期望有一个函数,它将您的graphql查询的结果传递为StaticQuery(签出React的docs on render props)。

例如,您可以这样重写它:

render

希望有帮助!