简体   繁体   English

NextJS,使用链接钩子访问站点时,useSWR 钩子在第一次加载时获取未定义的值

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

TLDR: If I access page directly via the link of the page, page loads without errors; TLDR:如果我直接通过页面链接访问页面,页面加载没有错误; If I access page via NextJS Link hook the page throws error:如果我通过 NextJS Link钩子访问页面,页面会抛出错误:

Cannot read properties of undefined (reading '0')无法读取未定义的属性(读取“0”)

I recognized that the site works normally if I go straight to the link that I want... It stops working when I'm calling components with Link tags in nextJS then it throws an error that it's in title... So if I go straight to the link everything works as expected maybe that is also the reason that the page works if I click on my link and then refresh it... So what could be the problem with Link tag?我认识到,如果我直接转到我想要的链接,该站点可以正常工作......当我在 nextJS 中调用带有Link标签的组件时它会停止工作,然后它会抛出一个错误,它在标题中......所以如果我去直接到链接一切都按预期工作也许这也是我点击我的链接然后刷新它时页面工作的原因......那么链接标签可能有什么问题?

Fetcher code:抓取代码:

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

Here is the useSWR part of my code:这是我的代码的 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>
  );
}

And this is the code for other component where I have Link hooks:这是我有链接钩子的其他组件的代码:

       <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>

Try to return JSX.Element instead of string on conditions blocks尝试在条件块上返回 JSX.Element 而不是字符串

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

And the critical issue here is when you visit page directly there's no prop defined so you need to make condition for it with default value这里的关键问题是当您直接访问页面时,没有定义 prop,因此您需要使用默认值为其设置条件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 useSWR Hook 返回 undefined - useSWR Hook returns undefined 在 useMemo 钩子内的反应路由器链接中使用时,状态未定义 - State is undefined when used in react router link inside useMemo hook useSWR 钩子行为不正常或可能过时的关闭 - useSWR hook behaving erratically or possible stale closure useSWR 在 nextjs 中使用 axios 返回未定义的数据 - useSWR returning undefined data with axios in nextjs 当导航参数更新时使用 useSWR 进行 api 调用,并将其值存储在带有 contextAPI 的自定义挂钩上 - Make api call with useSWR when navigation params updates and store his value on custom hook with contextAPI NEXTJS:无效的钩子调用 - NEXTJS: Invalid hook call 在自定义钩子中使用 nextjs 进行无效的钩子调用 - invalid hook call with nextjs inside custom hook NextJS - 未处理的运行时错误类型错误:将 class function 转换为挂钩 function 时无法读取未定义的属性(读取“长度”) - NextJS - Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'length') when converting a class function to hook function SWR,围绕 useSWR 钩子创建一个包装器以显示加载状态 - SWR, creating a wrapper around the useSWR hook to show loading state 我应该在这个包装 useSWR 的自定义钩子中测试什么? - What should i test in this custom hook that is wrapping useSWR?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM