2017-12-15 16 views
0

私は非常にジュニアであることに反応してスーパーです。reactjs google-distance-matrix更新コンポーネント

私はGoogleの距離行列apiの周りを遊んでいます。ユーザーはフォーム上で起点と目的地を入力し、イベントハンドラは値を行列関数に渡しますが、関数内では状態変数を更新できません。

どのような考えですか?

import React from 'react'; 
import GoogleMap from 'google-distance-matrix'; 
class SimpleForm extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     address: '', 
     dest:'', 
     distanceText:'testing the distance text' 
    } 
    this.handleFormSubmit = this.handleFormSubmit.bind(this); 

    this.onChange = (address) => this.setState({ address }); 
    this.changeDest = (dest) => this.setState({dest}); 
} 
handleFormSubmit = (event) => { 
    event.preventDefault()   
    GoogleMap.matrix(this.state.address, this.state.dest, function (err, distances) { 
     if (err) { 
      return console.log(err); 
     } 
     if(!distances) { 
      return console.log('no distances'); 
     } 
     if (distances.status == 'OK') { 
      if(distances.rows[0].elements[0]) { 
       var distance = distances.rows[0].elements[0].duration['text']; 
       this.setState({ 
        foundDistance: true, 
        distanceText: distance 

       }); 
      } 
     } 
    }); 

} 
+0

GoogleMap.matrixの「this」は、SimpleFormコンポーネントの「this」を指しません。行列関数の最後に.bind(this)を使用してみてください – Tobias

答えて

0

は、単純に(かなり標準パターンである)変数にthisをキャッシュするよりも、パフォーマンスヒットのよりしかし、わずかながあります。

また、this.stateで破壊を使用してください。

handleFormSubmit = (event) => { 
    const component = this 
    const { address, dest } = this.state 

    event.preventDefault()   

    GoogleMap.matrix(address, dest, function (err, distances) { 
     if (err) { 
      return console.log(err); 
     } 

     if(!distances) { 
      return console.log('no distances'); 
     } 

     if (distances.status == 'OK') { 
      if(distances.rows[0].elements[0]) { 
       var distance = distances.rows[0].elements[0].duration['text']; 

       component.setState({ 
        foundDistance: true, 
        distanceText: distance 
       }); 
      } 
     } 
    }); 
} 
0

GoogleMap.matrixの「this」はSimpleFormコンポーネントの「this」を指しません。それをバインド:バインド

... 
GoogleMap.matrix(...) 
... 
).bind(this) 
関連する問題