2017-11-24 5 views
-1

ReactJSアプリケーションでGoogleグラフを使用しようとしています。私は "react-google-charts"を使いたくありません。 私は私のindex.htmlで ...私はすでに全体のインターネットを検索し、これが私の現在のコードです:私が持っているReactJSでGoogleグラフを使用する

import React from 'react'; 
import {MainViewHeader} from './MainViewHeader'; 
import TouristService from '../../services/TouristService'; 
import Util from '../../services/Util'; 

google.charts.load('current', {'packages':['corechart']}); 

export class MainView extends React.Component { 
    constructor() { 
     super(); 
     this.state = { 
      touristInfos: [], 
      touristInfosHeader: [] 
     }; 
     google.charts.setOnLoadCallback(() => this.renderGoogleTable()); 
    } 

    componentDidMount() { 
     let touristInfos = TouristService.getAllTouristInfos(); 
     touristInfos.then(
      info => 
       this.setState({ 
        touristInfos: Util.getResults(info) 
       }) 
     ); 
     //this.renderGoogleTable(); 
    } 

    componentDidUpdate(){ 
     this.renderGoogleTable(); 
    } 

    renderGoogleTable(){ 
     let data = google.visualization.arrayToDataTable(this.state.touristInfos); 

     let table = new google.visualization.Table(document.getElementById('table_div')); 
     table.draw(data, {showRowNumber: true, width: '100%', height: '100%'}); 
    } 

    render() { 
     return (
      <div className="search-and-overview"> 
       <MainViewHeader /> 
       <div className="mid-region"> 
        <div className="content"> 
         <div className="problem-list"> 
          <div id="table_div"></div> 
         </div> 
        </div> 
       </div> 

      </div> 
     ); 
    } 
} 

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

<script type="text/javascript" src="https://www.google.com/jsapi?autoload= 
{'modules':[{'name':'visualization','version':'1.1','packages': 
['corechart']}]}"></script> 

とチャートを使用する私のコンポーネントは次のようになります私はこのバージョンを試しましたので、私は角度のGoogleグラフを使用するためのstackoverflowのポストで見つけたgoogle.charts.setOnLoadCallback(myGraphDrawingFunction)をどこでどのように使用するか分からない。 renderGoogleTable機能でthisを使用する必要があります。だから私は "定期的なsetOnLoadCallbackの方法"を使用して私はもうthisを使用することはできません。

私のクロムのdevのツールは、このエラー反応で

MainView.js:36 Uncaught (in promise) TypeError: google.visualization.Table is not a constructor 
    at MainView.renderGoogleTable (MainView.js:36) 
    at MainView.js:15 
    at <anonymous> 
+0

をあなたが機能bind' 'renderGoogleTable'または'へのパラメータとして 'this'を渡すことができます。 – Erin

答えて

0

に投げ、コンポーネントのライフサイクルを理解することは、あなたが主に必要な一つのことです。たとえば、jQueryでは、ready関数を使用して、DOMが完全にロードされたことを知ります。 reactでは、同等のものはcomponentDidMountです。

したがって、をcomponentDidMountに宣言することができます。

また、コンストラクタでメソッドを宣言し、thisをバインドすることを忘れないでください。

注:このようなことをcomponentWillMountでも行うことができますが、この場合はdiv table_divがまだロードされていないのでエラーが発生します。

this.renderGoogleTable = this.renderGoogleTable.bind(this)

すなわち現在のコンポーネントのライフサイクルの詳細を読むことができます:https://reactjs.org/docs/react-component.html#the-component-lifecycle

関連する問題