【发布时间】:2022-01-08 20:45:24
【问题描述】:
我最近升级到 Strapi 的新 v4,却发现它返回数据的新方式破坏了我的 Gatsby 应用程序。
新结构在数据中包含嵌套数组,我在使用 Gatsby 的 createPages 功能时遇到了问题。
这是来自 http://localhost:8000/___graphql 的有效查询
query MyQuery {
allStrapiArticles {
edges {
node {
data {
attributes {
title
author
content
}
id
}
}
}
}
}
这是该查询返回的内容(注意每个项目及其相关数据现在都在数组中):
{
"data": {
"allStrapiArticles": {
"edges": [
{
"node": {
"data": [
{
"attributes": {
"title": "Test Title",
"author": "Test Author",
"content": "Test Content"
},
"id": 1
}
]
}
}
]
}
},
}
来自 http://localhost:8000/___graphql 的代码导出器建议将下面的代码块与他们的 createPages 功能一起使用,但是使用它会返回以下错误:
TypeError: result.data.allStrapiArticles.forEach 不是函数
const path = require(`path`)
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
{
allStrapiArticles {
edges {
node {
data {
attributes {
title
author
content
}
id
}
}
}
}
}
`)
const templatePath = path.resolve(`PATH/TO/TEMPLATE.js`)
result.data.allStrapiJobs.forEach((node) => {
createPage({
path: `/careers/${node.id}`,
component: path.resolve(`src/templates/article/index.js`),
context: {
slug: node.id,
},
})
})
}
作为参考,在升级到 Strapi V4 之前,我在 gatsby-node.js 中使用 createPages 功能的代码块如下(请注意,返回的数据没有数组并且更易于使用):
exports.createPages = async ({ graphql, actions }) => {
const path = require(`path`)
const { createPage } = actions
return new Promise((resolve, reject) => {
graphql(`
query {
allStrapiArticles {
edges {
node {
id
}
}
}
}
`).then(result => {
result.data.allStrapiArticles.edges.forEach(({ node }) => {
createPage({
path: `/articles/${node.id}`,
component: path.resolve(`src/templates/article/index.js`),
context: {
id: node.id,
},
})
})
resolve()
})
}).catch(error => {
console.log(error)
reject()
})
}
const path = require(`path`)
const makeRequest = (graphql, request) =>
new Promise((resolve, reject) => {
// Query for nodes to use in creating pages.
resolve(
graphql(request).then(result => {
if (result.errors) {
reject(result.errors)
}
return result
})
)
})
有没有比我更有知识的人知道如何让它再次工作?这一直是很多挫折的根源。任何帮助将不胜感激!
【问题讨论】:
标签: javascript reactjs graphql gatsby strapi