【问题标题】:how to use Directus with gatsby如何在 gatsby 中使用 Directus
【发布时间】:2018-05-07 16:34:29
【问题描述】:

如何在getsby.js中使用Directus数据

我已经设置了一个 Directus 应用程序,并添加了表格和数据/列,但我不知道如何在 gatsby.js 中使用它,我在 jsx 中构建了一个这样的模板:

const path = require('path')

exports.createPages = ({ boundActionCreators, graphql }, { urlPrefix }) => {
 const { createPage } = boundActionCreators

return new Promise((resolve, reject) => {
resolve(
  graphql(
    `
      {
        allDirectusPost {
          edges {
            node {
              id
              title
              author
              content
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      console.error('GraphQL query returned errors')
      reject(result.errors)
    }

    result.data.allDirectusPost.edges.forEach(edge => {
      try {
        let node = edge.node
        let path = `posts/${node.id}`
        createPage({
          path,
          layout: 'index',
          component: path.resolve('src/templates/post.jsx'),
          context: {
            post: node,
          },
        })
        console.log(`Generated page '${path}'`)
      }
      catch (error) {
        console.error(`Failed to generate page posts/'${path}': ${error}`)
      }
    })
  })
)
})
}

我在 gatsby.js 中有一个像这样的主页静态站点

import React from 'react'
import Link from 'gatsby-link'
// import postsTemplate from '../templates/post.jsx'

const IndexPage = () => (
  <div>
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.000</p>
    <p>Now go build something great.</p>
    <post />
    <Link to="/page-2/">Go to page 2</Link>
  </div>
)

export default IndexPage

如何调用该 gatsby 文件中的 directus 数据?

【问题讨论】:

    标签: php jsx gatsby directus


    【解决方案1】:

    对于 Directus 表中的每个项目,将基于 src/templates/post.jsx 组件创建一个新页面。这将是一组完全独立于IndexPage 的页面。

    从 Directus 获取页面的步骤与从 Markdown 获取页面的步骤非常相似。我建议你再读一遍https://www.gatsbyjs.org/docs/adding-markdown-pages/(虽然看起来你确实读过它,因为你的gatsby-node.js 代码看起来像是从那里借来的)。在posts.jsx 中,您要查询allDirectusPost(edges: { node: {id: {eq: $path } } }),而不是查询markdownRemark(frontmatter: { path: { eq: $path } })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多