编程语言
首页 > 编程语言> > javascript-一旦外部js文件加载,React-仅运行文件(未定义gapi)

javascript-一旦外部js文件加载,React-仅运行文件(未定义gapi)

作者:互联网

我正在尝试将Gmail API与React.js一起使用.

我不断收到错误“未定义gapi”.我相信我的mail.js文件运行后会加载HTML中的client.js文件吗?

我该如何解决?

Index.html

...
<script src="https://apis.google.com/js/client.js"></script>

Index.js

import './Mail.js';

Mail.js

import { createAction, handleActions } from 'redux-actions'

const CLIENT_ID = '1.apps.googleusercontent.com'
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

export const SET_GMAIL_CREDENTIALS = 'SET_GMAIL_CREDENTIALS'
export const CHANGE_LOADING = 'CHANGE_LOADING'
export const SET_GMAIL_LABELS = 'SET_GMAIL_LABELS'
export const SELECT_GMAIL_LABEL = 'SELECT_GMAIL_LABEL'
export const SET_GMAIL_EMAILS = 'SET_GMAIL_EMAILS'

let defaultState = {
  profile: {
    emailAddress: ''
  },
  loading: true,
  labels: [],
  currentLabel: null,
  emails: []
}

export const connect = () => {
  return (dispatch, getState) => {
    dispatch(turnLoadingOn())
    gmailAuth(false, populateCredentials(dispatch), clearCredentials(dispatch))
  }
}...

解决方法:

我想你是正确的.我处理这些情况的方式是通过从React加载外部JS文件并在promise中使用它.

因此,您的流程应如下所示:

>反应应用程序负载
> React应用程序将您的文件注入HTML
>在步骤2的回调或.then()中执行您的操作

创建一个辅助函数.将其放在helpers / load-script之类的文件夹中.以下是该文件中应包含的所有代码:

export default function loadScript(url, cb) {

      var scr = document.createElement('script');
      scr.type = 'text/javascript';

      if (scr.readyState) { // IE
        scr.onreadystatechange = function() {
          if (scr.readyState ==`loaded' || scr.readyState ==='complete') {
            scr.onreadystatechange = null;
            cb();
          }
        };
      } else { // Others
        scr.onload = cb;
      }

      script.src = url;
      document.getElementsByTagName('head')[0].appendChild(scr);
    }

接下来,将该函数导入要使用的组件中:

import React from 'react';
import loadScript from 'helpers/load-script';

class testComponent extends React.Component {
    
  componentDidMount() {
    loadScript('https://apis.google.com/js/client.js', () => {
    // do mail api stuff here               
    });
  }
   
  render() {
    return (
      <div>hi there</div>
    );
  }
}

export default testComponent;

标签:reactjs,gmail-api,javascript
来源: https://codeday.me/bug/20191026/1937124.html