从 Gatsby 中的 graphQL 查询创建 slug

Creating slugs from graphQL query in Gatsby

我正在连接到一个数据库,这个查询显示了我想要的 ID:

allSongs {
        edges {
          node {
            id
          }
        }
      }

所以现在我希望能够像这样加载动态页面:
网站.com/song/6

其中“6”是上面的id。看起来我需要根据查询动态创建 slug,但我无法让它工作。任何帮助表示赞赏!

您可以在 gatsby-node.js 中使用 createPage api 并创建动态页面

// Create song pages dynamically
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const songTemplate = path.resolve(`src/templates/songs.js`)
  const result = await graphql(`
    query {
      allSongs {
        edges {
          node {
            id
          }
        }
      }
    }
  `)
  result.data.allSongs.edges.forEach(edge => {
    createPage({
      path: `/song/${edge.node.id}`,
      component: songTemplate,
    })
  })
}