如何解决NextJs 中的分页
我正在尝试对使用 React / NextJs - getServerSideProps
构建的应用程序中的一个页面进行分页。
第一步:创建分页组件
第 2 步:重定向到带有页码的 URL(基于用户点击)
第 3 步:它应该使用较新的页面值重新呈现 getServerSideProps
,但现在不会发生这种情况。
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,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,},};
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。