React JS 和 Google 电子表格:无法读取 Null 的属性“2”

Tej*_*sOS 4 google-sheets reactjs

我目前正在使用React JS 和 Google Spreadsheets,并且正在关注与本文类似的内容。但是,我遇到了问题。每当我尝试连接到电子表格时,我的 React 应用程序都会成功运行几秒钟,然后崩溃,并显示以下错误消息: 在此输入图像描述

目前,这是我的代码:

import {
  GoogleSpreadsheet
} from 'google-spreadsheet';

function App() {
  const setup = async () => {
    const doc = new GoogleSpreadsheet('my spreadsheet-id'); // Obviously putting in my real spreadsheet id and data instead of this in my real code
    await doc.useServiceAccountAuth({
      client_email: 'my client-email',
      private_key: 'my private-key'
    });

    await doc.loadInfo(); // loads document properties and worksheets

    const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
    console.log(sheet.title);
    console.log(sheet.rowCount);
  }
Run Code Online (Sandbox Code Playgroud)

我的应用程序函数确实有一个渲染方法,我最终运行设置函数来连接到我的电子表格。

有谁知道为什么会发生这种情况以及我该如何解决它?谢谢!

小智 8

一段时间后我发现了这一点......对于那些发现这个 StackOverflow 线程作为他们唯一希望的人,我将在这里留下这个答案以节省您的一些时间。

显然,如果您将私有令牌存储在 .env 中,则该\n字符将被解析为\\n. 您需要确保斜杠没有被转义。

对于我的项目,这是解决方案:

await doc.useServiceAccountAuth({
  client_email: 'my client-email',
  private_key: process.env.REACT_APP_SHEET_PRIVATE_KEY.replace(/\\n/g, '\n')
});
Run Code Online (Sandbox Code Playgroud)