如何在 gatsbyjs 中创建带参数的路由

How to create routes with params in gatsbyjs

我想在我的 gatsby 生成的网站中创建一个使用 slug 作为参数的路由。

我有一份位于路线 /projects/<slug> 上的项目列表。

通常使用 React router 我会创建这样的路由:

<Route exact path='/projects/:project' component={Projects} /> 

看来在 gatsby 中,我必须在 ./pages 目录下创建一个新文件并创建一个新路由。我有一个名为 projects 的页面,我尝试在其中查找路由参数,但似乎只得到 404 页面。

// ./pages/projects.js

class SingleProject extends Component {

  state = {
    project: {}
  }

  componentDidMount(){
    const project = this.props.projects.find(project => project.slug === this.props.match.params.project)
    this.setState({project})
  }

  render() {
    return (
      <div className="single-project" >
      </div>
    )
  }
}

export default SingleProject;

如何在 gatsby 中使用带参数的路由?

我刚刚遇到 client only routes 但我想这些路由不会是静态生成的。

我会有一个预定义的 slug 列表,所以也许有办法为每个项目 slug 创建一个页面?我想我可以在 ./pages/projects/<slug> 中为我拥有的每个项目手动创建一个文件?

您需要使用 Gatsby 在 gatsby-node.jscreatePages API. There is a guide in the Gatsby documentation that shows you can achieve exactly this. Here's an even simpler example 中从类似问题中为您提供的 createPage 方法。

export const createPages = ({ actions }) => {
  const { createPage } = actions;

  createPage({
    path: '/projects/hello-world',
    component: SingleProject,

    // Send additional data to page component
    context: {
      id: 'hello-world',
    },
  });
};