Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

What is the correct folder structure in Next.js for routes with query parameters?

Next.js already documents correct usage of nested api's in their documentation here but one thing not covered there is the usage of query parameters. I have two routes. First one is mysite.com/posts which displays all the posts. Other one is mysite.com/posts?id=12 where you only get to see that specific post. What could be the correct folder structure to place my js file in there?

Right now the folder structure I have is :

pages -- folder
 posts -- folder
  [id].js -- file
  index.js -- file

Even though I have a feeling that this should be the correct way it doesn't work. Whenever I hit mysite.com/posts?id=12 I get mysite.com/posts and never get to see the page with the id. Any idea on what am I doing wrong here?

question from:https://stackoverflow.com/questions/66065433/what-is-the-correct-folder-structure-in-next-js-for-routes-with-query-parameters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to pass query parameter as per your folder structure i.e mysite.com/posts/12

As per documentation,Any route like /post/1, /post/abc, etc. will be matched by pages/post/[id].js. The matched path parameter will be sent as a query parameter to the page, and it will be merged with the other query parameters.

For example, the route /post/abc will have the following query object:

{ "id": "abc" }

Similarly, the route /post/abc?foo=bar will have the following query object:

{ "foo": "bar", "id": "abc" }

However, route parameters will override query parameters with the same name. For example, the route /post/abc?id=123 will have the following query object:

{ "pid": "abc" }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...