2017-12-21 15 views
3

状態をコールバック関数から設定する方法を理解できません。デフォルトでGoogleプレイスAPIコールに基づいて状態を更新します

Googleは、私が知りたいのは何get data from their place API

に私たちは、このコードを与えるです:

  • がどのように私はそのAPIから受信したデータに基づいて、ここでは「いるisOpen」の状態を更新することができますか?私はその後、宣言する状態「いるisOpen」(真/偽)を使用するつもりだ「これは」グローバルな状態

  • を参照していないとして、私は「this.setState」を行うことはできません

    • 条件付きJSXを持つ変数

      export default class IndexPage extends Component { 
          constructor(props) { 
          super(props); 
          this.state = { 
           isOpen: false, 
          }; 
      } 
      
      
      componentDidMount() { 
      let map = new window.google.maps.Map(document.getElementById("map"), { 
      
      }); 
      const request = { placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4" }; 
      const getPlaceById = new google.maps.places.PlacesService(map).getDetails(
      request, 
      callback 
      ); 
      
      function callback(place, status) { 
          if (status == google.maps.places.PlacesServiceStatus.OK) { 
          console.log(place.opening_hours.open_now); //returns true or false 
      
          //set isOpen to state 
      
          } 
      } 
      } 
      } 
      

答えて

1

コンポーネントにバインドせずにコールバックを宣言すると、 '未定義のsetState'エラーが返されます。

あなたの反応コンポーネントのクラスメソッドとしてコールバック関数を宣言します。次のようにcomponentDidMount内側その後、

class X extends React.Component { 
    ... 

    callback(place, status) { 
     if (status == google.maps.places.PlacesServiceStatus.OK) {    
      // set state here 
      this.setState({ isOpen: place.opening_hours.open_now}) 
     } 
    } 

    ... 
} 

()の呼び出しは、あなたのコールバックメソッドをバインドします

componentDidMount() { 
    const map = new window.google.maps.Map(document.getElementById("map"), {});  
    const request = { placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4" }; 
    const getPlaceById = new google.maps.places.PlacesService(map).getDetails(
     request, 
     // you need to bind `this` to callback function to use callback in HTML DOM 
     (place, status) => this.callback(place, status) 
    ); 
} 
0

基本的に、あなたはより多くの情報については、以下の

const getPlaceById = new 
google.maps.places.PlacesService(map).getDetails(
request, 
this.callback 
); 

を編集する必要がありますコンストラクタ

this.callback = this.callback.bind(this); 

の内側にあなたのコールバックにこれを結合し、https://reactjs.org/docs/handling-events.htmlを読みます

関連する問題