簡體   English   中英

NextJS,使用鏈接鈎子訪問站點時,useSWR 鈎子在第一次加載時獲取未定義的值

[英]NextJS, useSWR hook gets undefined values on first load when accesing site with Link hook

TLDR:如果我直接通過頁面鏈接訪問頁面,頁面加載沒有錯誤; 如果我通過 NextJS Link鈎子訪問頁面,頁面會拋出錯誤:

無法讀取未定義的屬性(讀取“0”)

我認識到,如果我直接轉到我想要的鏈接,該站點可以正常工作......當我在 nextJS 中調用帶有Link標簽的組件時它會停止工作,然后它會拋出一個錯誤,它在標題中......所以如果我去直接到鏈接一切都按預期工作也許這也是我點擊我的鏈接然后刷新它時頁面工作的原因......那么鏈接標簽可能有什么問題?

抓取代碼:

const fetcher = async () => {
  const response1 = await fetch("API1");
  const data1 = await response1.json();

  const response3 = await fetch("API2");
  const data3 = await response3.json();

  const response4 = await fetch("API3");
  const data4 = await response4.json();

  const props = {
    showItemsOnOrder: data1,
    dashboardCardInfo: data3,
    dashboardGraph: data4,
  };
  return props;
};

這是我的代碼的 useSWR 部分:

export default function Dashboard(props) {
  const {data, error} = useSWR("data", fetcher);

  useEffect(() => {
    //Pusher.logToConsole = true;
    var pusher = new Pusher("pshr", {
      cluster: "eu",
    });
    const channel = pusher.subscribe("chnl");
    channel.bind("chnl", function (data) {
      console.log(data);
      mutate("data");
    });
  }, []);

  if (error) return "Error";
  if (!data) return "Loading";

  console.log(data);
  return (
    <Fragment>
      <Head>
        <title>Dashboard</title>
        <link rel="icon" href="/favicon.ico" />
       
      </Head>

      <LayoutDashboard restaurantData={props?.restaurantData[0]}>
        <DashboardPage
          orders={data?.showItemsOnOrder}
          dashboardCards={data?.dashboardCardInfo}
          ordersGraph={data?.dashboardGraph}
        />
      </LayoutDashboard>
    </Fragment>
  );
}

這是我有鏈接鈎子的其他組件的代碼:

       <Link
       href={{
              pathname: "/restaurant/[restaurantName]/dashboard/",
              query: {restaurantName: restaurantName},
            }}
          >
            <div
              className={
                router.pathname == "/restaurant/[restaurantName]/dashboard"
                  ? "text-blue-600 bg-gray-50"
                  : "text-gray-700 "
              }
            >
              <div className="flex p-3  space-x-4 0 hover:bg-gray-50 hover:text-blue-600  cursor-pointer">
                <DonutLargeIcon className=" text-gray-300" />
                <p className="">Dashbord</p>
              </div>
            </div>
          </Link>

嘗試在條件塊上返回 JSX.Element 而不是字符串

  if (error) return <div>Error</div>;
  if (!data) return "<div>Loading</div>;

這里的關鍵問題是當您直接訪問頁面時,沒有定義 prop,因此您需要使用默認值為其設置條件

  <LayoutDashboard restaurantData={props?.restaurantData[0] || defaultValue}>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM