【问题标题】:Gapi is not defined in react app to acces google sheets api反应应用程序中未定义 Gapi 以访问 google sheet api
【发布时间】:2021-10-10 00:46:27
【问题描述】:

我正在尝试将数据从 React.js 网络应用程序中的 HTML 表单发送到谷歌表格。

我已经在 index.html 中添加了脚本标签(在 <head><body> 中尝试过),但 gapi 仍然未定义。

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()"
    onreadystatechange="if (this.readyState === 'complete') this.onload()">
  </script>
  <div id="root"></div>
</body>

在组件中我这样做:

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.onFormSubmit = this.onFormSubmit.bind(this); 
  }

  componentDidMount() {
    this.handleClientLoad();
  }

  handleClientLoad = () => {
    gapi.load("client:auth2", this.initClient);
  };
  updateSignInStatus() {}
  initClient = () => {
    gapi.client
      .init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        scope: SCOPE,
        discoveryDocs: [
          "https://sheets.googleapis.com/$discovery/rest?version=v4",
        ],
      })
      .then(() => {
        gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSignInStatus);
        this.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      });
  };

  onFormSubmit(submissionValues) {
    const params = {
      spreadsheetId: SPREADSHEET_ID,
      range: "Sheet1",
      valueInputOption: "RAW",
      insertDataOption: "INSERT_ROWS", 
    };

    const valueRangeBody = {
      majorDimension: "ROWS", 
      values: [submissionValues], 
    };

    let request = gapi.client.sheets.spreadsheets.values.append(
      params,
      valueRangeBody
    );
    request.then(
      function (response) {
        console.log(response.result);
      },
      function (reason) {
        console.error("error: " + reason.result.error.message);
      }
    );
  }
  render() {
    return (
      <form className="Form" onSubmit={this.onFormSubmit}>
   ...)};
}

我也尝试过window.gapi,但没有结果。 我知道在组件之前没有加载 gapi,但我不知道如何解决。

【问题讨论】:

    标签: javascript html reactjs google-api-js-client


    【解决方案1】:

    你可以使用gapi-script包而不是使用脚本标签来加载gapi,因为这个包立即提供了gapi,所以你不必等待任何脚本加载,只需导入并使用

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2019-02-20
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多