reactjs google-距离矩阵更新组件

reactjs google-distance-matrix updating component

我是 reactjs 的超级新手,我还很初级。

我正在玩 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"。绑定它:

...
GoogleMap.matrix(...)
...
).bind(this)

与简单地在变量中缓存 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
                }); 
            }
        } 
    });
}