【发布时间】:2021-04-02 05:20:56
【问题描述】:
我正在尝试使用谷歌图表,但我不断收到此错误
Failed to compile.
src\Map.js
Line 14:13: 'google' is not defined no-undef
Line 17:13: 'google' is not defined no-undef
Line 25:28: 'google' is not defined no-undef
Line 42:29: 'google' is not defined no-undef
我在此处关注此链接:https://developers.google.com/chart/interactive/docs/quick_start。这是我的 Map.js 文件
import React, { useState, useEffect } from 'react';
function Map(props) {
useEffect(() => {
const script = document.createElement('script');
script.src = "https://www.gstatic.com/charts/loader.js";
script.async = true;
script.setAttribute('id', 'gcs-5645')
document.body.appendChild(script);
document.getElementById('gcs-5645').addEventListener('load', () => {
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
});
}, []);
return <div></div>;
}
export default Map;
我只是想创建一个基本的饼图。我的理解是,我必须等到脚本加载完毕,然后才能全局访问“google”对象。但是为什么还没有定义呢?
我是否以正确的方式思考这个问题?有没有更好的方法来做到这一点?
【问题讨论】:
-
我认为问题是 google 未定义 XD
-
您需要从库或文件中导入 google 变量
-
那么我的问题是,我该怎么做?
-
我刚刚测试了你的代码。它工作正常。一旦
load事件触发,google将在全球范围内可用 -
尝试从
window对象访问google。喜欢window.google
标签: javascript reactjs google-visualization