GatsbyJS从Restful API获取数据 [英] GatsbyJS getting data from Restful API

查看:86
本文介绍了GatsbyJS从Restful API获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React和GatsbyJS的新手.我很困惑,无法以一种简单的方式弄清楚如何从第三方Restful API加载数据.

I am new in both React and GatsbyJS. I am confused and could not make figuring out in a simple way to load data from third-party Restful API.

例如,我想从randomuser.me/API获取数据,然后能够使用页面中的数据.

For example, I would like to fetch data from randomuser.me/API and then be able to use the data in pages.

我们这样说:

  import React from 'react'
  import Link from 'gatsby-link'

  class User extends React.Component {
    constructor(){
      super();
      this.state = {
        pictures:[],
      };

    }

    componentDidMount(){
      fetch('https://randomuser.me/api/?results=500')
      .then(results=>{
        return results.json();
      })
      .then(data=>{
        let pictures = data.results.map((pic,i)=>{
            return(
              <div key={i} >
                <img key={i} src={pic.picture.medium}/>
              </div>
            )
        })
        this.setState({pictures:pictures})
      })
    }

    render() {
      return (<div>{this.state.pictures}</div>)
    }
  }

  export default User;

但是我想得到GraphQL的帮助,以便进行&过滤排序用户等…..

But I would like to get the help of GraphQL in order to filter & sort users and etc…..

能否请您帮我找到如何获取数据并将其插入gatsby-node.js上的GraphQL的示例?

Could you please help me to find the sample to how I can fetch data and insert them into GraphQL on gatsby-node.js?

推荐答案

如果要使用GraphQL来获取数据,则必须创建一个sourceNode.关于创建源插件的文档可以为您提供帮助

If you want to use GraphQL to fetch your data, you have to create a sourceNode. The doc about creating a source plugin could help you.

请按照以下步骤操作,以使用Gatsby项目中的GraphQL查询randomuser数据.

Follow these steps to be able to query randomuser data with GraphQL in your Gatsby project.

在您的根项目文件夹中,将此代码添加到gatsby-node.js:

In your root project folder, add this code to gatsby-node.js:

const axios = require('axios');
const crypto = require('crypto');

exports.sourceNodes = async ({ boundActionCreators }) => {
  const { createNode } = boundActionCreators;

  // fetch raw data from the randomuser api
  const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
  // await for results
  const res = await fetchRandomUser();

  // map into these results and create nodes
  res.data.results.map((user, i) => {
    // Create your node object
    const userNode = {
      // Required fields
      id: `${i}`,
      parent: `__SOURCE__`,
      internal: {
        type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
        // contentDigest will be added just after
        // but it is required
      },
      children: [],

      // Other fields that you want to query with graphQl
      gender: user.gender,
      name: {
        title: user.name.title,
        first: user.name.first,
        last: user.name.last,
      },
      picture: {
        large: user.picture.large,
        medium: user.picture.medium,
        thumbnail: user.picture.thumbnail,
      }
      // etc...
    }

    // Get content digest of node. (Required field)
    const contentDigest = crypto
      .createHash(`md5`)
      .update(JSON.stringify(userNode))
      .digest(`hex`);
    // add it to userNode
    userNode.internal.contentDigest = contentDigest;

    // Create node with the gatsby createNode() API
    createNode(userNode);
  });

  return;
}

我使用axios来获取数据,因此您需要安装它:npm install --save axios

I used axios to fetch data so you will need to install it: npm install --save axios

说明:

目标是为要使用的每条数据创建每个节点. 根据 createNode文档,您必须为对象提供很少的对象必填字段(id,父项,内部,子项).

Explanation:

The goal is to create each node for each piece of data you want to use. According to the createNode documentation, you have to provide an object with few required fields (id, parent, internal, children).

一旦从randomuser API获取结果数据,您只需要创建此节点对象并将其传递给createNode()函数.

Once you get the results data from the randomuser API, you just need to create this node object and pass it to the createNode() function.

我们在这里映射到您想要获得500个随机用户的结果https://randomuser.me/api/?results=500.

Here we map to the results as you wanted to get 500 random users https://randomuser.me/api/?results=500.

使用必填字段和通缉字段创建userNode对象. 您可以根据要在应用程序中使用的数据添加更多字段.

Create the userNode object with the required and wanted fields. You can add more fields depending on what data you will want to use in your app.

只需使用Gatsby API的createNode()函数创建节点.

Just create the node with the createNode() function of the Gatsby API.

完成此操作后,运行gatsby develop并转到 http://localhost:8000/___ graphql .

Once you did that, run gatsby develop and go to http://localhost:8000/___graphql.

您可以使用GraphQL来创建理想的查询.当我们命名节点对象'RandomUser'internal.type时,我们可以查询allRandomUser来获取数据.

You can play with GraphQL to create your perfect query. As we named the internal.type of our node object 'RandomUser', we can query allRandomUser to get our data.

{
  allRandomUser {
    edges {
      node {
        gender
        name {
          title
          first
          last
        }
        picture {
          large
          medium
          thumbnail
        }
      }
    }
  }
}

3)在您的盖茨比页面中使用此查询

在页面中,例如src/pages/index.js,使用查询并显示数据:

3) Use this query in your Gatsby page

In your page, for instance src/pages/index.js, use the query and display your data:

import React from 'react'
import Link from 'gatsby-link'

const IndexPage = (props) => {
  const users = props.data.allRandomUser.edges;

  return (
    <div>
      {users.map((user, i) => {
        const userData = user.node;
        return (
          <div key={i}>
            <p>Name: {userData.name.first}</p>
            <img src={userData.picture.medium} />
          </div>
        )
      })}
    </div>
  );
};

export default IndexPage

export const query = graphql`
  query RandomUserQuery {
    allRandomUser {
      edges {
        node {
          gender
          name {
            title
            first
            last
          }
          picture {
            large
            medium
            thumbnail
          }
        }
      }
    }
  }
`;

就是这样!

这篇关于GatsbyJS从Restful API获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆