【问题标题】:React component failed to compile because 'google' is not defined (google charts)React 组件无法编译,因为未定义“google”(谷歌图表)
【发布时间】: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


【解决方案1】:

问题 如果您尝试动态添加 scripts 并添加 onload 侦听器,则它正在加载脚本,但 google var 已绑定到窗口对象,因此如果您想访问,则必须使用 window.google.&lt;functions&gt; 否则输出将成为你得到的那个人

灵魂解决方案 因为我有多个组件,所以我只是将其设置为 state 可能不是一个好主意,但解决了我的目的,您可以直接使用 window.google 对象

代码


index.html

<head>
    <script type="text/javascript" id="gc" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

</script>
</head>

app.js

export default function App() {
  const [gc, setGc] = useState(undefined);
  useEffect(() => {
    // this loads google charts
    setGc(window.google);
    console.log("googlecharts", gc);
  }, []);

控制台输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 2023-04-05
    • 1970-01-01
    • 2016-07-25
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多