Javascript 如何正确使用CreatePagesAPI以编程方式创建页面?
我正在创建我的公文包,在这里我想为我的博客和项目创建两个单独的选项卡。理想情况下,我应该以编程方式为这些选项卡中的每一项创建页面 然后,我就可以通过遵循盖茨比官方教程来为我的博客标签中的项目做到这一点。然而,当我尝试对“项目”选项卡上的项目执行相同的操作时,我能够让它工作,但不知何故,博客选项卡的初始设置同时停止工作Javascript 如何正确使用CreatePagesAPI以编程方式创建页面?,javascript,node.js,reactjs,gatsby,Javascript,Node.js,Reactjs,Gatsby,我正在创建我的公文包,在这里我想为我的博客和项目创建两个单独的选项卡。理想情况下,我应该以编程方式为这些选项卡中的每一项创建页面 然后,我就可以通过遵循盖茨比官方教程来为我的博客标签中的项目做到这一点。然而,当我尝试对“项目”选项卡上的项目执行相同的操作时,我能够让它工作,但不知何故,博客选项卡的初始设置同时停止工作 const path= require('path') exports.createPages=({graphql,actions})=>{ const {createPa
const path= require('path')
exports.createPages=({graphql,actions})=>{
const {createPage}=actions
const blogPost= path.resolve('./src/components/blogComponents/blog-post.js')
return new Promise((resolve,reject)=>{
graphql(`
{
allContentfulBlog{
edges{
node{
slug
}
}
}
}
`).then(results=>{
// console.log(results)
if(results.error){
reject(results.error)
}
// create blog post pages
const posts=results.data.allContentfulBlog.edges
// console.log(post)
posts.forEach((post,index)=>{
console.log(`showing slugs: ${post.node.slug}`)
// const previous= index === posts.length-1?null: posts[index+1].node
// const next= index === 0?null: posts[index-1].node
createPage({
path:`/${post.node.slug}`,
component:blogPost ,
context:{
slug:post.node.slug,
// previous,
// next
}
})
})
}) .then(resolve)
}) }
//creating pages for projects
exports.createPages=({graphql,actions})=>{
const {createPage}=actions
const projectPage= path.resolve('./src/components/projectComponents/project.js')
return new Promise((resolve,reject)=>{
graphql(`
{
allContentfulProjects{
edges{
node{
slug
}
}
}
}
`).then(results=>{
if(results.error){
reject(results.error)
}
projects= results.data.allContentfulProjects.edges
projects.forEach(project=>{
createPage({
path:`/${project.node.slug}`,
component:projectPage ,
context:{
slug:project.node.slug,
}
})
})
}).then(resolve)
})
}
我的假设是,对于每个想要设置的编程页面,导出一个单独的createPages API是可行的方法,但结果却遇到了这个问题。我搜索了文档,但找不到解决问题的部分。
exports.createPages=
是一个赋值,因此在编写第二个函数时基本上覆盖了第一个函数
当我必须创建两种不同类型的页面时,我只是将所有内容都放到一个查询中,然后对嵌套对象执行foreach
exports.createPages=({graphql,actions})=>{
const{createPage}=操作;
返回图(`
质疑{
所有的标记{
边缘{
节点{
田地{
鼻涕虫
}
}
}
}
奥尔拉特森{
边缘{
节点{
名称
img
}
}
}
}
`)。然后(结果=>{
result.data.allMarkdownRemark.edges.forEach(({node})=>{
创建页面({
路径:node.fields.slug,
组件:path.resolve(`./src/templates/blog post.js`),
背景:{
slug:node.fields.slug
}
});
});
result.data.allRatsJson.edges.forEach(({node})=>{
创建页面({
路径:node.name.toLowerCase(),
组件:path.resolve(`./src/templates/rat.js`),
背景:{
name:node.name,
img_url:node.img
}
});
});
});
};
哦,我现在明白了!让我试一试,看看进展如何。