如何将Google API与React正确集成 [英] How to correctly integrate google API with React

查看:90
本文介绍了如何将Google API与React正确集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经集成了 Google Analytics(分析)Embed API 与我的React应用程序配合使用,我就可以正确地绘制图形.这是我的容器,该容器通过组件UsersChart:

I've integrated the Google analytics Embed API with my React app and I'm able to render correctly a graph. This is my container, which renders a line chart through the component UsersChart:

class StatsContainer extends Component {
    constructor(props) {
        super(props);
        initAnalyticsAPI();
    }

    render() {
      return (
         <Query query={GET_ACCESS_TOKEN}>
          {({ loading: loadingToken, error: errorToken, data: { getAnalyticsAccessToken } }) => (
              <Query query={GET_BASIC_STATS}>
                  {({ loading: loadingStats, error: errorStats, data: { getBasicStats } }) => {
                    if (loadingToken || loadingStats) return 'Loading...';
                    if (errorStats) return `Error! ${errorStats.message}`;
                    else if (errorToken) return `Error! ${errorToken.message}`;

                    const token = getAnalyticsAccessToken;

                    return (
                      <Fragment>
                        <div className="stats-container">
                          {/* ... */
                          <UsersCharts token={token} />
                        </div>
                      </Fragment>
                    );
                  }}
              </Query>
        )}
        </Query>
    );
  }
}

initAnalyticsAPI只是使用官方代码将脚本追加到文档中:

initAnalyticsAPI just appends the script to the document, using the official code:

function loadGA() {
   /* eslint-disable */
    (function(w,d,s,g,js,fs) {
        g = w.gapi || (w.gapi={});
        g.analytics = { q:[], ready: function(f) { this.q.push(f); }};
        js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
        js.src='https://apis.google.com/js/platform.js';
        fs.parentNode.insertBefore(js,fs);
        js.onload = function() {
            g.load('analytics');
        };
      }(window, document, 'script'));
    /* eslint-enable */
}

export default function initialize() {
    if (typeof window === 'undefined') {
        return false;
    }

    // avoid downloading the library multiple times if it's already defined
    if (_.isEmpty(window.gapi)) {
        loadGA();
    }

    return window.gapi;
}

为简短起见,UsersCharts立即呈现图表使用的容器,而Google API会在就绪后立即加载它:

To keep it short, UsersCharts renders immediately the container used by the chart, while Google API will load it as soon as it's ready:

class UsersCharts extends Component {
    constructor(props) {
        super(props);
        this.chart = null;
    }

    componentWillUnmount() {
       // how to properly unmount it?
    }

    render() {
        const { token } = this.props;
        window.gapi.analytics.ready(() => {
            /**  Authorize the user with an access token obtained server side. */
            window.gapi.analytics.auth.authorize({
                serverAuth: {
                    access_token: token,
                },
            });

            this.chart = new window.gapi.analytics.googleCharts.DataChart({
            query: {
               ...
            },
            chart: {
                ...
            },
         });
        this.chart.execute();
      });

      return (
          <Fragment>
              <div id="chart-container" />
          </Fragment>
      );
    }
}

问题是,当我转到另一部分时,有时会出现以下错误,这意味着由于呈现了另一个组件,因此应用程序内部不再存在图表的容器.我该怎么做才能正确卸下组件?我搜索了一个API,该API可以让我注销图表,或者至少捕获错误,但我找不到它. 谢谢

The issue is that sometimes I get the following error when I go to another section, which implies that the container for the chart doesn't exist anymore inside the app since another component is rendered. What could I do to properly unmount the component? I search for an API which could allow me to unregister the chart, or at least to catch the error but I wasn't able to find it. Thanks

推荐答案

通过映射两个

Doing a refactoring of UsersChart by mapping the status of both the library and the component, I was able to get rid of all the warnings:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class UsersCharts extends Component {
    constructor(props) {
        super(props);

        this._isMounted = false;
        this.state = {
            ready: false,
        };
    }

    componentDidMount() {
        this._isMounted = true;
        window.gapi.analytics.ready(() => {
            console.log('Ready to do fireworks');
            if (this._isMounted) {
                 this.setState({ ready: true });
            }
        });
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    render() {
        const { token } = this.props;

       if (this.state.ready) {
        /**  auth and draw chart */

        this.chart.execute();
       }

       return <div id="chart-container" />;
   }
}

这篇关于如何将Google API与React正确集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆