javascript 将props传递给URL中带有查询的子页面会导致431请求头字段太大

xeufq47z  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(104)

我有一个名为campaigns的页面,在索引页面上,我想将数据转发到我的动态页面[campaignId].tsx
设法看到我的动态页面上的数据,但url链接变得太长,直到它得到一个HTTP状态码431头太长,每当我试图刷新页面。
下面是我的index.tsx

const DisplayCampaigns = ({
  title,
  isLoading,
  campaigns,
}: DisplayCampaignsProps) => {
  

  return (
    <div>
      <h1 className="font-epilogue font-semibold text-[18px] text-white text-left">
        {title} ({campaigns.length})
      </h1>
      <div className="flex flex-wrap mt-[20px] gap-[26px]">
        {isLoading && (
          <Image
            src={loader}
            alt="loader"
            className="w-[100px] h-[100px] object-contain"
          />
        )}

        {!isLoading && campaigns.length === 0 && (
          <p className="font-epilogue font-semibold text-[14px] leading-[30px] text-[#818183]">
            You have not created any campaigns yet
          </p>
        )}

        {!isLoading &&
          campaigns.length > 0 &&
          campaigns.map((campaign: any) => (
            <Link
              href={{
                pathname: `/campaigns/${campaign.title}`,
                query: { ...campaign },
              }}
            >
              <FundCard key={campaign.pId} {...campaign} />
            </Link>
          ))}
      </div>
    </div>
  );
};

有没有一种方法我可以重构它,使网址可以缩短,仍然能够通过 prop 到我的动态页面?

huwehgph

huwehgph1#

正如您所做的那样,该URL将包含campaign所具有的属性数量的查询字符串,其长度将与所有这些属性的长度总和一样长。而服务器(在刷新页面时调用)只为请求的标头保留有限的内存。这是你的问题。
您只能将活动的id放在URL中。在[campaignId.tsx]上获取它,然后,您可以通过网络调用、从上下文或使用getServerSideProps等服务器端函数在useEffect中获取活动。
为此,请将index.tsx中的重定向更改为:

<Link
  href={{
    pathname: `/campaigns/${campaign.id}`,
  }}
>
  <FundCard key={campaign.pId} {...campaign} />
</Link>

然后在[campaignId.tsx]上使用fetch获取活动,或者使用传递的id从全局状态获取活动:

import { useRouter } from "next/router";
import { useEffect, useState } from "react";

export default function Campaign() {
  const router = useRouter();
  const [campaign, setCampaign] = useState(null);
  useEffect(() => {
    if (router.isReady) {
      // You can fetch it from an API, or from a global state, like a context
      fetch(`/api/${router.query.campaignId}`)
        .then((res) => res.json())
        .then((data) => setCampaign(data));
    }
  }, [router]);
  if (!campaign) {
    return "Loading...";
  }
  return <div>{campaign.title}</div>;
}

或者,在[campaignId.tsx]上,使用getServerSideProps并在服务器上获取活动:

export default function Campaign({ campaign }) {
  return <div>{campaign.title}</div>;
}

export async function getServerSideProps(context) {
  const res = await fetch(`/api/${context.query.campaignId}`);
  const data = await res.json();
  return {
    props: { campaign: data }, // will be passed to the page component as props
  };
}

相关问题