Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

请问next.js在getStaticProps里怎样获取路由参数

在首页进行搜索时,带参跳到搜索页,在搜索页需要知道搜索的内容,然后通过内容进行数据获取,但是在getStaticProps里无法获取路由参数,这时是在node环境里运行的


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

1 Answer

0 votes
by (71.8m points)

你要注意,next是分为纯静态渲染和SSR服务端渲染
你使用getStaticProps是开启纯静态渲染,是无法获得动态的路由参数进行解析,除非你使用了动态路径解析。
像你的需求你,需要将数据获取放到getServerSideProps中,而不要使用getStaticProps
这样你可以从中获得context,进而取得路径参数:


 export async function getServerSideProps(context) {
   console.log(context)
   //here,you can fetch data by context.query
   return {
     props: {
      query:context.query    
      }, // will be passed to the page component as props
   }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...