演示版本 Next^14.2.3
为什么需要 pathname
页面太多,想要自动化设置 document.title 以及设置 Open Graph 的 url (用户点击社交媒体的链接,就可以自动跳到详情页,而不是开发者指定的页面)。这两个需求都是需要在页面的 head 标签里面配置。
而 generateMetadata 是 Next 官方提供静态函数不支持 hook。
解决办法
打印 generateMetadata 的第二个参数,可以看到如下结果:
一个异步的对象上有一个 symbol,它的值也是一个对象,这个对象有一个参数 urlPathname 里面就有我们需要的参数。
可以根据如下函数获取这个路径:
/**
* Get the pathname from the metadata state
* This dives into async storage of promise state to get the pathname
*
* This is much more performant that using headers() from next as this doesn't opt out from the cache
* @param state
*/
export const getPathnameFromMetadataState = (state: any): string | undefined => {
const res = Object.getOwnPropertySymbols(state || {})
.map(p => state[p])
.find(state => state?.hasOwnProperty?.("urlPathname"))
return res?.urlPathname.replace(/\?.+/, "")
}