2 回答

TA貢獻1856條經驗 獲得超11個贊
如果您真的想將查詢參數用于分頁(類似/foo?page=2
)和 SSG,我剛剛想出了一個解決方法。
您可以使用 Next JSrewrites
和redirects
功能。
首先,使用/foo/[page].js
文件格式并靜態生成所有頁面,正如hangindev.com 解釋的那樣。
然后,在next.config.js
文件中,您必須導出兩個函數:async redirects()
和async rewrites()
.
module.exports = {
....
async redirects() {
return [
{
source: "/foo/1",
destination: "/foo?page=1",
permanent: true,
},
{
source: "/foo/2",
destination: "/foo?page=2",
permanent: true,
},
{
source: "/foo/3",
destination: "/foo?page=3",
permanent: true,
},
];
},
async rewrites() {
return [
{
source: "/foo",
has: [{ type: "query", key: "page", value: "1" }],
destination: "/foo/1",
},
{
source: "/foo",
has: [{ type: "query", key: "page", value: "2" }],
destination: "/foo/2",
},
{
source: "/foo",
has: [{ type: "query", key: "page", value: "3" }],
destination: "/foo/3",
},
];
},
};
該redirects()功能確保用戶無法看到/foo/2格式的頁面,因為他們被重定向到/foo?page=2. 該rewrites()函數顯示URL的/foo/2頁面內容。/foo?page=2

TA貢獻1878條經驗 獲得超4個贊
因為getStaticProps在構建時運行,所以它不會接收僅在請求期間可用的數據,例如查詢參數 或 HTTP 標頭,因為它會生成靜態 HTML。 文檔
您可以做的一件事是不要將頁面編號放在查詢中,而是將其作為路由參數,即用戶將訪問/3而不是/?page=3.
要實現它,你需要[page].js在pages目錄中創建一個并導出一個getStaticPaths函數:
export async function getStaticPaths() {
// query Strapi to calculate the total page number
return {
paths: [
{ params: { page: '1' } },
{ params: { page: '2' } },
{ params: { page: '3' } }
],
fallback: true or false // See the "fallback" section in docs
};
}
還有一個getStaticProps功能:
export async function getStaticProps(context) {
const { page } = context.params;
// fetch page data
return {
props: { ... },
}
}
在 Next.js文檔getStaticPaths中了解更多信息。getStaticProps
添加回答
舉報