私は非常にジュニアであることに反応してスーパーです。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
});
}
}
});
}
GoogleMap.matrixの「this」は、SimpleFormコンポーネントの「this」を指しません。行列関数の最後に.bind(this)を使用してみてください – Tobias