问题
I want to create a route that uses a slug as a parameter in my gatsby generated website.
I have a list of projects that sit on the route /projects/<slug>
.
Usually with react router I would create a route like so:
<Route exact path='/projects/:project' component={Projects} />
It seems in gatsby, I have to create a new file under the ./pages
directory and that creates a new route. I have a page called projects
where I try do a look up on the route param but only seem to get the 404 page.
// ./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;
How can I have routes with parameters in gatsby?
I have just come across client only routes but I guess these routes wont be statically generated.
I will have a predefined list of slugs so perhaps there is a way to create a page for each of the project slugs? I guess I could manually create a file within ./pages/projects/<slug>
foreach project I have?
回答1:
You'll want to use the createPage
method that Gatsby gives you inside gatsby-node.js
's createPages API. There is a guide in the Gatsby documentation that shows you can achieve exactly this. Here's an even simpler example from a similar question.
export const createPages = ({ actions }) => {
const { createPage } = actions;
createPage({
path: '/projects/hello-world',
component: SingleProject,
// Send additional data to page component
context: {
id: 'hello-world',
},
});
};
来源:https://stackoverflow.com/questions/51988998/how-to-create-routes-with-params-in-gatsbyjs