将道具传递到 URL 中带有查询的子页面会导致 431 请求标头字段太大

问题描述 投票:0回答:1

我有一个名为活动的页面,在索引页面上我想将数据转发到我的动态页面

[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>
  );
};

有没有一种方法可以重构它,以便可以缩短 url 并仍然能够将 props 传递到我的动态页面?

javascript reactjs next.js web3
1个回答
0
投票

您只能将活动的

id
放在网址中。抓住
id
上的
[campaignId.tsx]
,然后,您可以通过网络调用、从上下文或服务器端功能(如
useEffect
)在
getServerSideProps
中获取活动。

为此,将

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
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.