You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-google-calendar-api集成Google Calendar时遇ReferenceError: gapi未定义

解决React集成Google Calendar时的ReferenceError: gapi is not defined错误

错误原因

react-google-calendar-api依赖Google官方的gapi和gapi.auth2脚本,但你的代码未提前加载这些脚本,导致执行库方法时找不到gapi对象;同时代码里存在拼写错误:apiKet应为apiKey。

修复步骤

  • 第一步:加载Google gapi脚本
    在项目的public/index.html文件中,添加Google的API脚本到<body>标签末尾(确保在React代码执行前加载完成):

    <script src="https://apis.google.com/js/api.js"></script>
    <script src="https://accounts.google.com/gsi/client"></script>
    
  • 第二步:修正代码拼写错误
    将配置里的apiKet改为apiKey:

    const config = {
      clientId: clientId,
      apiKey: apiKey, // 修正拼写错误
      scope: 'https://www.googleapis.com/auth/calendar',
      discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
    };
    
  • 第三步:确保gapi加载完成后再调用库方法
    直接在useEffect中调用方法可能因为脚本未加载完成报错,可调整逻辑等待脚本加载完毕:

    const GoogleCalender = () => {
      useEffect(() => {
        const initCalendar = () => {
          apiCalendar.handleAuthClick();
          apiCalendar.listEvents({
            timeMin: new Date().toISOString(),
            timeMax: new Date().toISOString(),
            showDeleted: true,
            maxResults: 10,
            orderBy: 'updated',
          }).then((result) => {
            console.log(result, 'ggggggggggggggg');
          });
        };
    
        // 检查gapi是否已加载
        if (window.gapi) {
          initCalendar();
        } else {
          // 监听api.js脚本加载完成事件
          const gapiScript = document.querySelector('script[src="https://apis.google.com/js/api.js"]');
          gapiScript.addEventListener('load', initCalendar);
        }
      }, []);
    
      return <div>Google Calendar Integration</div>;
    };
    

内容的提问来源于stack exchange,提问作者John Anwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:45:18