如何正确地将 google API 与 React 集成
How to correctly integrate google API with React
我已经将 Google analytics Embed API 与我的 React 应用程序集成在一起,并且能够正确呈现图形。这是我的容器,通过组件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
只是将脚本追加到文档中,使用官方代码:
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 将在准备就绪后立即加载它:
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 可以让我取消注册图表,或者至少可以捕获错误但我找不到它。
谢谢
通过映射两个 the library and the component 的状态对 UsersChart
进行重构,我能够摆脱所有警告:
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 analytics Embed API 与我的 React 应用程序集成在一起,并且能够正确呈现图形。这是我的容器,通过组件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
只是将脚本追加到文档中,使用官方代码:
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 将在准备就绪后立即加载它:
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 可以让我取消注册图表,或者至少可以捕获错误但我找不到它。 谢谢
通过映射两个 the library and the component 的状态对 UsersChart
进行重构,我能够摆脱所有警告:
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" />;
}
}