NextJs 中的分页
Pagination in NextJs
我正在尝试对使用 React / NextJs 构建的应用程序中的一个页面进行分页 - getServerSideProps
。
第 1 步:创建分页组件
第 2 步:重定向到带有页码的 URL(基于用户点击)
第 3 步:它应该使用更新的页面值重新呈现 getServerSideProps
,但现在不会发生这种情况。
我当前的代码块(服务器端道具 - API 调用):
export const getServerSideProps = async (ctx) => {
try {
const APIKey = await getCookieAPIKey(ctx);
const user = await getCookieUser(ctx);
const dataSSR = await getDataSSR(
APIKey,
'/xyz/xyz/read/',
user.user_id,
'user_id',
ctx.query.page,
ctx.query.limit
);
// console.log(d, "data")
return {
props: {
dataSSR
}
};
} catch (err) {
...
return { props: { fetchError: err.toString() } };
}
};
export const getDataSSR = async (APIKey, path, id, idString, page, limit) => {
//generate URL path for fetch
const base_url = `${ENDPOINT}/services`;
let url;
if (id && !idString && !page) {
url = base_url + path + '?key=' + APIKey + '&id=' + id;
} else if (id && idString && page) {
url = base_url + path + '?key=' + APIKey + `&${idString}=` + id + '&page=' + page + `&limit=${!limit ? '24' : limit}`;
} else if (id && idString && !page) {
url = base_url + path + '?key=' + APIKey + `&${idString}=` + id + '&page=0' + `&limit=${!limit ? '24' : limit}`;
}
else {
url = base_url + path + '?key=' + APIKey + '&page=' + page + `&limit=${!limit ? '10' : limit}`;
}
我按照this tutorial进行分页。
修改点击方法语句:
<ReactNextPaging
itemsperpage={itemsperpage}
nocolumns={nocolumns}
items={items}
pagesspan={pagesspan}
>
{({
getBackButtonProps,
getFwdButtonProps,
getFastFwdButtonProps,
getSelPageButtonProps,
nopages,
inipagearray,
pagesforarray,
currentpage,
noitems,
initialitem,
lastitem,
goBackBdisabled,
goFastBackBdisabled,
goFwdBdisabled,
goFastFwdBdisabled
}) => (
<tbody style={{ alignItems: "center", margin: "auto auto" }}>
{/* {items.slice(initialitem, lastitem).map((item, index) => {
return item;
})} */}
{noitems > 0
? [
<tr key={"pagingrow" + 100} >
<td colSpan={nocolumns} style={{ textAlign: "center" }}>
<button
style={buttonStyles(goBackBdisabled)}
{...getBackButtonProps()}
disabled={goBackBdisabled}
>
{"<"}
</button>
{Array.from(
{ length: pagesforarray },
(v, i) => i + inipagearray
).map(page => {
return (
<button
key={page}
{...getSelPageButtonProps({ page: page })}
disabled={currentpage == page}
style={{ margin: "0.5em", backgroundColor: "transparent", border: "none" }}
onClick={e => page != currentpage ? pageNumClick(page, e, currentpage) : {}}
>
{page}
</button>
);
})}
<button
style={buttonStyles(goFwdBdisabled)}
{...getFwdButtonProps()}
disabled={goFwdBdisabled}
>
{">"}
</button>
</td>
</tr>
]
: null}
</tbody>
)}
</ReactNextPaging>
页面重定向句柄代码:
const pageNumClick = (page, e, currentpage) => {
let el = document.getElementsByClassName(`.clickable-page-${page}`)
console.log(el)
e.target.style.backgroundColor = "#353E5A";
currentpage = page;
console.log(page, "clicked page number", e.target, currentpage)
//Redirects to the URL with clicked page number
router.push({
pathname: router.pathname,
query: { show: showname, page: page }
})
refreshData(); // Try to refresh props once the URL is changed
}
const refreshData = () => {
router.replace(router.asPath);
console.log('refreshed')
}
尝试解决:
- 添加了
refreshData
方法以根据 this. 在 URL 更改时调用 ServerSideProps
- 尝试将
getServerSideProps
更改为 getInitialProps
- 但没有成功
任何帮助或链接将不胜感激,自 3 天以来一直坚持这项任务
问题是由 refreshdata 函数引起的,router.asPath 将有您当前的 url。
下面的代码对我来说工作正常。
function ProductDetail({ products, page,limit }) {
const router = useRouter();
const pageNumClick = (page, limit) => {
router.push({
pathname: router.pathname,
query: { limit: limit, page: page },
});
};
return (
<div>
<div onClick={() => pageNumClick(parseInt(page) + 1, limit)}>Next page</div>
<div onClick={() => pageNumClick(parseInt(page) - 1, limit)}>
Previous page
</div>
{products ? JSON.stringify(products) : <></>}
</div>
);
}
export async function getServerSideProps({ params, query, ...props }) {
const products = await getProducts(query.limit, query.page);
return {
props: {
products: products ? products : {},
page: query.page,
limit: query.limit,
},
};
}
我正在尝试对使用 React / NextJs 构建的应用程序中的一个页面进行分页 - getServerSideProps
。
第 1 步:创建分页组件
第 2 步:重定向到带有页码的 URL(基于用户点击)
第 3 步:它应该使用更新的页面值重新呈现 getServerSideProps
,但现在不会发生这种情况。
我当前的代码块(服务器端道具 - API 调用):
export const getServerSideProps = async (ctx) => {
try {
const APIKey = await getCookieAPIKey(ctx);
const user = await getCookieUser(ctx);
const dataSSR = await getDataSSR(
APIKey,
'/xyz/xyz/read/',
user.user_id,
'user_id',
ctx.query.page,
ctx.query.limit
);
// console.log(d, "data")
return {
props: {
dataSSR
}
};
} catch (err) {
...
return { props: { fetchError: err.toString() } };
}
};
export const getDataSSR = async (APIKey, path, id, idString, page, limit) => {
//generate URL path for fetch
const base_url = `${ENDPOINT}/services`;
let url;
if (id && !idString && !page) {
url = base_url + path + '?key=' + APIKey + '&id=' + id;
} else if (id && idString && page) {
url = base_url + path + '?key=' + APIKey + `&${idString}=` + id + '&page=' + page + `&limit=${!limit ? '24' : limit}`;
} else if (id && idString && !page) {
url = base_url + path + '?key=' + APIKey + `&${idString}=` + id + '&page=0' + `&limit=${!limit ? '24' : limit}`;
}
else {
url = base_url + path + '?key=' + APIKey + '&page=' + page + `&limit=${!limit ? '10' : limit}`;
}
我按照this tutorial进行分页。
修改点击方法语句:
<ReactNextPaging
itemsperpage={itemsperpage}
nocolumns={nocolumns}
items={items}
pagesspan={pagesspan}
>
{({
getBackButtonProps,
getFwdButtonProps,
getFastFwdButtonProps,
getSelPageButtonProps,
nopages,
inipagearray,
pagesforarray,
currentpage,
noitems,
initialitem,
lastitem,
goBackBdisabled,
goFastBackBdisabled,
goFwdBdisabled,
goFastFwdBdisabled
}) => (
<tbody style={{ alignItems: "center", margin: "auto auto" }}>
{/* {items.slice(initialitem, lastitem).map((item, index) => {
return item;
})} */}
{noitems > 0
? [
<tr key={"pagingrow" + 100} >
<td colSpan={nocolumns} style={{ textAlign: "center" }}>
<button
style={buttonStyles(goBackBdisabled)}
{...getBackButtonProps()}
disabled={goBackBdisabled}
>
{"<"}
</button>
{Array.from(
{ length: pagesforarray },
(v, i) => i + inipagearray
).map(page => {
return (
<button
key={page}
{...getSelPageButtonProps({ page: page })}
disabled={currentpage == page}
style={{ margin: "0.5em", backgroundColor: "transparent", border: "none" }}
onClick={e => page != currentpage ? pageNumClick(page, e, currentpage) : {}}
>
{page}
</button>
);
})}
<button
style={buttonStyles(goFwdBdisabled)}
{...getFwdButtonProps()}
disabled={goFwdBdisabled}
>
{">"}
</button>
</td>
</tr>
]
: null}
</tbody>
)}
</ReactNextPaging>
页面重定向句柄代码:
const pageNumClick = (page, e, currentpage) => {
let el = document.getElementsByClassName(`.clickable-page-${page}`)
console.log(el)
e.target.style.backgroundColor = "#353E5A";
currentpage = page;
console.log(page, "clicked page number", e.target, currentpage)
//Redirects to the URL with clicked page number
router.push({
pathname: router.pathname,
query: { show: showname, page: page }
})
refreshData(); // Try to refresh props once the URL is changed
}
const refreshData = () => {
router.replace(router.asPath);
console.log('refreshed')
}
尝试解决:
- 添加了
refreshData
方法以根据 this. 在 URL 更改时调用 - 尝试将
getServerSideProps
更改为getInitialProps
- 但没有成功
ServerSideProps
任何帮助或链接将不胜感激,自 3 天以来一直坚持这项任务
问题是由 refreshdata 函数引起的,router.asPath 将有您当前的 url。 下面的代码对我来说工作正常。
function ProductDetail({ products, page,limit }) {
const router = useRouter();
const pageNumClick = (page, limit) => {
router.push({
pathname: router.pathname,
query: { limit: limit, page: page },
});
};
return (
<div>
<div onClick={() => pageNumClick(parseInt(page) + 1, limit)}>Next page</div>
<div onClick={() => pageNumClick(parseInt(page) - 1, limit)}>
Previous page
</div>
{products ? JSON.stringify(products) : <></>}
</div>
);
}
export async function getServerSideProps({ params, query, ...props }) {
const products = await getProducts(query.limit, query.page);
return {
props: {
products: products ? products : {},
page: query.page,
limit: query.limit,
},
};
}