Gatsby.js 未来的网页09:Index页面

栏目: 前端 · 发布时间: 5年前

内容简介:上一篇中,我们用GraphiQL测试了GraphQL的查询。今天,我们就要用这些查询来打造一个Index页面。打开/pages/index.js,之前我们加入了Link,现在要使用GraphQL来取得资料,你可以参考/templates/post.js,两者很类似,差别在于,post是取得单篇文章资料,而index是取得多篇文章资料:

Gatsby.js 未来的网页09: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页面看到那两篇文章的连结。

本文参与 iT邦帮忙铁人赛繁体


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beautiful Code

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》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码