内容简介:上一篇中,我们用GraphiQL测试了GraphQL的查询。今天,我们就要用这些查询来打造一个Index页面。打开/pages/index.js,之前我们加入了Link,现在要使用GraphQL来取得资料,你可以参考/templates/post.js,两者很类似,差别在于,post是取得单篇文章资料,而index是取得多篇文章资料:
上一篇中,我们用GraphiQL测试了GraphQL的查询。今天,我们就要用这些查询来打造一个Index页面。
视频教学连结
加入GraphQL
打开/pages/index.js,之前我们加入了Link,现在要使用GraphQL来取得资料,你可以参考/templates/post.js,两者很类似,差别在于,post是取得单篇文章资料,而index是取得多篇文章资料:
export const pageQuery = graphql` query IndexQuery { allMarkdownRemark(limit: 10) { edges { node { id frontmatter { title path } } } } } `
其中id是自动产生的,用于Link连结,因为每个component都需要一个唯一的Key。
接着就可以将GraphQL取得的数据交给IndexPage使用,完全的index.js程式如下:
import React from 'react' import { Link } from 'gatsby' import Layout from '../components/layout' const IndexPage = ({data}) => ( <Layout> <h1>Hi guys</h1> <p>Welcome to your new Gatsby site.</p> <p>Now go build something great.</p> <Link to="/page-2/">Go to page 2</Link> <Link to="/page-3/">Go to page NEW</Link> <h2>Index</h2> {data.allMarkdownRemark.edges.map(post => ( <Link key={post.node.id} to={post.node.frontmatter.path}> {post.node.frontmatter.title} </Link> ))} </Layout> ) export const pageQuery = graphql` query IndexQuery { allMarkdownRemark(limit: 10) { edges { node { id frontmatter { title path } } } } } ` export default IndexPage
执行 gatsby develop
之后,便能在index页面看到那两篇文章的连结。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 即时通讯工具 V-IM 0.5.0 发布,主要解决网页模式刷新页面状态丢失问题
- 防止网页被其他网页iframe嵌套的思考与实现
- 响应式网页设计–css设置网页字体大小自适应
- R网页采集:解决网页分页与网址超链接问题
- 网页制作用什么软件?制作网页的常用软件工具分享
- 如何写优美的网页
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Beautiful Code
Greg Wilson、Andy Oram / O'Reilly Media / 2007-7-6 / GBP 35.99
In this unique work, leading computer scientists discuss how they found unusual, carefully designed solutions to difficult problems. This book lets the reader look over the shoulder of major coding an......一起来看看 《Beautiful Code》 这本书的介绍吧!