0

我正在尝试在使用 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}`;
  }

我按照本教程进行分页。

通过修改 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. 添加了基于thisrefreshData在 URL 更改时调用的方法。ServerSideProps
  2. 尝试更改getServerSidePropsgetInitialProps- 没有运气

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

4

1 回答 1

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,
    },
  };
}
于 2021-06-27T12:13:25.330 回答