reactjs Next.js“引用错误:未使用gapi-script定义”窗口

jdg4fx2g  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(145)

我已经尝试了每一个解决办法,但是,由于某种原因,我一直得到下面的截图错误...不知道为什么?
服务器错误
参考错误:未定义窗口此错误是在生成页面时发生的。所有控制台日志都将显示在终端窗口中。调用堆栈eval node_modules/gapi-script/gapi脚本. js(1:9)。/node_modules/gapi-script/gapi脚本. js文件:[...]/.next/server/pages/[...]/[id].js(98:1)webpack_require文件:/[...]/.next/server/webpack-runtime.js(33:42)

  1. import { useEffect } from 'react';
  2. import Head from 'next/head';
  3. import styles from '../../../styles/Home.module.css';
  4. import { GoogleLoginButton } from '../../../components';
  5. import { gapi } from 'gapi-script';
  6. export async function getServerSideProps(context: any) {
  7. const res = await fetch(
  8. `http://localhost:3000/api/...`,
  9. );
  10. const data = await res.json();
  11. return { props: { data } };
  12. }
  13. const GAPI_CONFIG = {
  14. apiKey: process.env.GOOGLE_API_KEY,
  15. clientId: process.env.CLIENT_ID,
  16. scope: process.env.GOOGLE_SCOPE,
  17. };
  18. export default function NblOneTeam({ data }: any) {
  19. useEffect(() => {
  20. function start() {
  21. gapi.client.init(GAPI_CONFIG);
  22. }
  23. gapi.load('client:auth2', start);
  24. });
  25. return (
  26. <div className={styles.container}>
  27. <Head>
  28. <title>NBL1 Scout Generator</title>
  29. <meta name="description" content="Generated by create next app" />
  30. <link rel="icon" href="/favicon.ico" />
  31. </Head>
  32. <main className={styles.main}>
  33. <h1>Hi NBL1 Teams</h1>
  34. <GoogleLoginButton />
  35. {data.map((player: any) => {
  36. return <h2>{player.name}</h2>;
  37. })}
  38. </main>
  39. </div>
  40. );
  41. }

正如我提到的,我已经尝试了如下的变通方法:Window is not defined in nextJS

rfbsl7qr

rfbsl7qr1#

NextJs在服务器端构建页面,而窗口只能在客户端访问。当页面加载时,窗口在NextJs中始终是未定义的
解决方法是动态导入gapi。

  1. useEffect(() => {
  2. async function start() {
  3. const gapi = (await import('gapi-script')).default
  4. gapi.client.init(GAPI_CONFIG);
  5. }
  6. gapi.load('client:auth2', start);
  7. }, []);

相关问题