ReactJS Google-Distance-Matrix更新组件



我是Am Am Freathior的ReactJ Super New。

我在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
                }); 
            }
        } 
    });
}

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

" this"在googlemap.matrix中没有指向简单形式组件的"此"。绑定它:

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

最新更新