【问题标题】:Pagination in NextJsNextJs 中的分页
【发布时间】:2021-09-09 23:32:42
【问题描述】:

我正在尝试在使用 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进行分页。

加上对click方法语句的修改:

<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')
  }

尝试解决:

  1. 添加了refreshData 方法以在基于this 的URL 更改时调用ServerSideProps
  2. 尝试将 getServerSideProps 更改为 getInitialProps - 没有成功

任何帮助或链接将不胜感激,自 3 天以来一直坚持该任务

【问题讨论】:

    标签: pagination next.js react-pagination


    【解决方案1】:

    问题是由 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,
        },
      };
    }
    

    【讨论】:

    • 谢谢...我的错,getserversideProp 每次都返回新获取的记录,这是我的组件渲染(状态)没有得到更新,知道我做错了什么吗? @Anish
    • 我无法按原样运行您的代码,但我可以观察到您没有在 pageNumClick 中使用限制,并且 refreshData 在触发路由器之前使用 url 刷新。推
    猜你喜欢
    • 2021-11-10
    • 1970-01-01
    • 2021-07-15
    • 2022-01-04
    • 2020-10-30
    • 2021-09-07
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多