在geocodeByAddress函数中两次设置状态

时间:2018-11-22 17:00:01

标签: javascript reactjs

我正在尝试根据geocodeByAddress react-places-autocomplete函数的返回值将状态设置为旅行对象。纬度和经度的返回值映射到拾取对象和纬度/经度参数。但是,两次setState不起作用。谁能看到解决方法?

class App extends Component {
constructor(props) {
    super(props);

    this.state = {
        trip: {
            pickUp: null,
        },
        pickupLatitudeDisplay: '',
        pickupLongitudeDisplay: '',
}
}
handlePickupSelect = address => {
    const {
        pickupLatitudeDisplay,
        pickupLongitudeDisplay,
    } = this.state;

    geocodeByAddress(address)
        .then(results => getLatLng(results[0]))
        .then(results => {
            console.log('Success', results)
            this.setState({
                pickupLatitudeDisplay: results.lat,
                pickupLongitudeDisplay: results.lng,
            }, () => {
                this.setState({
                    trip: {
                        ...this.state.trip,
                        pickUp: {
                            ...this.state.trip.pickUp,
                            latitude: pickupLatitudeDisplay,
                            longitude: pickupLongitudeDisplay,
                        },
                    }
                })
            })
        })
        .catch(error => console.error('Error', error));}

0 个答案:

没有答案