【发布时间】:2018-08-24 06:08:04
【问题描述】:
我是 React 和 GatsbyJS 的新手。我很困惑,无法以一种简单的方式从第三方 Restful API 加载数据。
例如,我想从 randomuser.me/API 获取数据,然后能够在页面中使用这些数据。
让我们这样说:
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 的帮助,以便对用户进行过滤和排序等...... ..
您能帮我找到如何获取数据并将它们插入到gatsby-node.js GraphQL 的示例吗?
【问题讨论】:
-
你不能在运行时使用 GatsbyJS 的 GraphQL 接口,只能在构建时使用。但是,如果你真的需要 GraphQL,你可以使用第三方库。
-
感谢您的 PM。但我不打算制作运行时 GraphQL,为了更好的解释,我检查了这个例子 github.com/gatsbyjs/gatsby/tree/master/examples/… 。 ,但这只是从内容定制到特定 API,我想构建一个类似的示例来从任何 Restful API 加载数据。我检查了 GatsbyJS 插件部分,有插件 'gatsby-source-api' 但我无法使其工作或在我的示例应用程序中运行
-
这些插件和示例旨在在构建时使用(不是在
componentDidMount()上,不是在fetch上,我不确定我是否清楚地解释自己)。恐怕目前没有用于自定义 REST API 调用的通用插件。