2

我开始将CleverTap for Web Web SDK 快速入门指南集成到我的应用程序中Next.js

谷歌搜索后发现一些包,如clevertap-web-sdk,clevertap-react并决定去(集成)使用clevertap-web-sdk npm包。遵循文档作为方式(更具体地遵循React Example,因为它建议)但有问题。

换了另一个包clevertap-react。这里也发现了同样的问题。

ReferenceError:未定义窗口


_app.tsx

import React, { useEffect, useState } from "react";
import type { AppProps } from "next/app";
import { appWithTranslation } from "next-i18next";
import { Hydrate, QueryClient, QueryClientProvider } from "react-query";
import { ReactQueryDevtools } from "react-query/devtools";

import nextI18NextConfig from "../next-i18next.config.js";

import "tailwindcss/tailwind.css";
import "styles/globals.scss";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import { useRouter } from "next/router";
import SvgPageLoading from "components/color-icons/PageLoading";
// import { PageLoading } from "components/color-icons/";

import { DefaultSeo } from 'next-seo';
import SEO from 'next-seo.config';
import ClevertapReact from 'clevertap-react';

ClevertapReact.initialize("TEST-61c-a12");

function MyApp({ Component, pageProps }: AppProps) {
  const [queryClient] = React.useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            refetchOnWindowFocus: false,
            staleTime: Infinity,
          },
        },
      })
  );
  const router = useRouter();
  const [isAnimating, setIsAnimating] = useState(false);
  useEffect(() => {
    const handleStart = () => {
      setIsAnimating(true);
    };
    const handleStop = () => {
      setIsAnimating(false);
    };

    router.events.on("routeChangeStart", handleStart);
    router.events.on("routeChangeComplete", handleStop);
    router.events.on("routeChangeError", handleStop);

    return () => {
      router.events.off("routeChangeStart", handleStart);
      router.events.off("routeChangeComplete", handleStop);
      router.events.off("routeChangeError", handleStop);
    };
  }, [router]);
  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <DefaultSeo {...SEO} />
        <Component {...pageProps} />
        {isAnimating && (
          <div className="fixed top-0 left-0 flex items-center justify-center w-screen h-screen overflow-visible bg-white bg-opacity-80 z-overlay top-z-index">
            <SvgPageLoading />
          </div>
        )}
        <ReactQueryDevtools initialIsOpen={false} />
      </Hydrate>
    </QueryClientProvider>
  );
}

export default appWithTranslation(MyApp, nextI18NextConfig);

4

1 回答 1

2

这是因为 Next 试图在服务器上渲染您的组件,并且服务器上不存在 window 对象。

你能试一下吗:

import dynamic from 'next/dynamic'

const ClevertapReact = dynamic(
  () =>
    import("clevertap-react").then((clevertap) =>
      clevertap.initialize("YOUR_ACCOUNT_ID")
    ),
  { ssr: false }
);
于 2021-12-15T10:31:41.337 回答