【问题标题】:How to pass data fetched from graphql API to React class component如何将从 graphql API 获取的数据传递给 React 类组件
【发布时间】:2020-09-23 10:11:08
【问题描述】:

根据 gatsby 文档,我们可以将数据作为数据参数传递给功能组件(来源:https://github.com/gatsbyjs/gatsby/blob/master/examples/using-gatsby-source-graphql/src/pages/index.js),我如何将这些数据传递给类组件

    import React from "react"
    import Layout from "../../components/layout"
    import { Row, Col, Button, Form, Pagination } from "react-bootstrap"
    import { Link } from "gatsby"
    import { Subscribe } from "../../components/stories/subscribe"

   export default class Home extends React.Component {
      state = {
      }


      render(data) {
        return (
          <Layout>
            <Subscribe />
            <Form>
              <Row>IIIIIIIIIIIIIIIIIIIIIIIIIIIIII</Row>
              <Row>{JSON.stringify(data)}</Row>
              <Row>IIIIIIIIIIIIIIIIIoooIIIIIIIIIIIII</Row>
              <Row></Row>
              </div>
            ))}
            <Row>
              <Pagination>
                <Pagination.Prev> Prev</Pagination.Prev>
              </Pagination>
              <Col xs={8}></Col>
              <Pagination>
                <Pagination.Next> Next</Pagination.Next>
              </Pagination>
            </Row>
          </Layout>
        )
      }
    }

    export const query = graphql`
      query {
        api {
          publicfeed {
            total
            posts {
              id
              content
            }
          }
        }
      }
    `

【问题讨论】:

  • this.props.data ?

标签: reactjs graphql gatsby


【解决方案1】:

页面查询的数据在 props 中可用,而不是作为渲染的参数。你可以像this.props.data一样访问它

export default class Home extends React.Component {
      state = {
      }


      render() {
        const { data } = this.props;
        return (
          <Layout>
            <Subscribe />
            <Form>
              <Row>IIIIIIIIIIIIIIIIIIIIIIIIIIIIII</Row>
              <Row>{JSON.stringify(data)}</Row>
              <Row>IIIIIIIIIIIIIIIIIoooIIIIIIIIIIIII</Row>
              <Row></Row>
              </div>
            ))}
            <Row>
              <Pagination>
                <Pagination.Prev> Prev</Pagination.Prev>
              </Pagination>
              <Col xs={8}></Col>
              <Pagination>
                <Pagination.Next> Next</Pagination.Next>
              </Pagination>
            </Row>
          </Layout>
        )
      }
    }

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 2020-12-29
    • 2019-09-24
    • 1970-01-01
    • 2019-04-13
    • 2019-06-18
    • 2016-10-28
    • 2020-06-01
    • 2018-07-14
    相关资源
    最近更新 更多