NextJS。如何获得动态页面的规范URL?

时间:2020-09-09 05:19:32

标签: reactjs seo next.js

在我使用nextjs 9.4之前 next-absolute-url程序包,它在getInitialProps中提供原始信息。

nextsjs 9.5 由于使用自动优化,我们使用getServerSideProps和getStaticProps。该软件包不支持这些方法,并且返回undefined。

我的问题是,如果我们具有动态页面,则可以使用next-seo说post / [pid] .tsx,我需要使用规范的url,我该如何使用getStaticProps或getServerSideProps生成

还有另一个问题在这里没有回应 How to access canonical URL in Next.js with Automatic Static Optimization turned on?

2 个答案:

答案 0 :(得分:0)

如果您需要从网址中获取 pid ,则需要在动态路由页面中使用 router.query , 这会给你一个像 {"pid":123}

// post/[pid].tsx

import { useRouter } from 'next/router'

getStaticProps(){
 const router = useRouter();
 const pid = router.query.pid;
 return {props:{pid}}
}

我在此网址中找到了完美的文档-https://nextjs.org/docs/routing/dynamic-routes

答案 1 :(得分:0)

因此,在更新(从应用程序中删除Redux)之后,next-absoulute-url在getServerSideProps上确实起作用。

如果应用程序状态不是太复杂,则带有Hooks的React-context API可以很好地工作。在这里阅读 https://kentcdodds.com/blog/application-state-management-with-react