如何添加上下文到createPage Gatsby?

时间:2019-10-31 16:55:46

标签: gatsby

我遇到了这个问题,不确定什么地方出问题了。我为在线课程设计了一个项目。所以我有一个带有按钮的页面,该页面指的是预订

 <Link to={`/preorder/${slug}`} state={{ title: `${title}`}} className={styles.button}>Buy a course </Link> 

因此在预订时,我有一个网址,例如preorder/currentSlug

如果我先在课程卡上单击,然后在“购买”按钮上,一切正常,这意味着我有上一个链接的标题,这就是我想要的。

 const Preorder = ({ location }) => { return (
<>
  <NoSSR>
     <h4 className={styles.title}>{location.state.title}</h4>
  </NoSSR>
<> )};

但是问题是,在新的浏览器窗口中打开链接preorder/currentSlug时,标题的名称未定义。我猜想createPage方法中上下文的问题。这是我的代码:

  const path = require(`path`);
  exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions;
  const coursePost = path.resolve(`./src/templates/course.js`);
  const preorder = path.resolve(`./src/templates/preorder/index.js`);
  return graphql(`
    {
      allContentfulCourse {
        edges {
          node {
            title
            tutor
            job
            slug
            team {
              job
              photo
              role
              desc
              name
            }
            logo {
              description
              file {
                url
              }
            }
          }
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      throw result.errors;
    }

    const courses = result.data.allContentfulCourse.edges;

    courses.forEach(course => {
      createPage({
        path: course.node.slug,
        component: coursePost,
        context: {
          slug: course.node.slug
        }
      });
    });

    courses.forEach(course => {
      createPage({
        path: `preorder/${course.node.slug}`,
        component: preorder,
        context: {
          course
        }
      });
    });
  });
};

您有任何想法我在做什么错吗?

0 个答案:

没有答案
相关问题