微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NextJs 中的分页

如何解决NextJs 中的分页

我正在尝试对使用 React / NextJs - getServerSideProps 构建的应用程序中的一个页面进行分页

第一步:创建分页组件
第 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,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')
  }

尝试解决

  1. 添加refreshData 方法以在基于 this 的 URL 更改时调用 ServerSideProps
  2. 尝试将 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?