Axios不会立即更新状态

时间:2020-07-17 20:01:55

标签: javascript reactjs typescript axios google-maps-react

我正在使用Google Maps React API。我不确定自己在做什么错,但是当我尝试使用Axios更新时,纬度和经度仍然是0、0。

import React, {Component} from 'react'
import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react';
import axios from 'axios'

const mapStyle = {
    width: '100%',
    height: '90%'
}

export class MapContainer extends Component<{google}, { map: google.maps.Map<Element>, latitude: number, longitude: number}>{
    onMapClicked: mapEventHandler;
    onMarkerClick: markerEventHandler;
    map?: google.maps.Map | google.maps.StreetViewPanorama
    marker?: google.maps.Marker
    onInfoWindowClose: any;

    constructor(props){
        super(props);
        this.state = {
            map: null,
            latitude: 0,
            longitude: 0
        }
        this.componentDidMount = this.componentDidMount.bind(this);
    }
    
    componentDidMount(){
        axios
        .get('https://api.##########.com/admin/user', {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer e-------------IU'
            },
            params: {
                'userId':'c------------------------------------d'
            }
        })
        .then(
            resp => {
                this.setState({
                    latitude: Number(resp.data.location.latitude),
                    longitude: Number(resp.data.location.longitude)
                })
                console.log("Before:" + this.state.latitude + " and " + this.state.longitude);
            })
        .catch(err => console.log(err))
    }

    render(){
        console.log("After:" + this.state.latitude + " and " + this.state.longitude);
        return(
            <>
                <Map google={google} 
                     zoom={16}
                     draggable
                     initialCenter={{
                        lat: this.state.latitude,
                        lng: this.state.longitude
                     }}
                     onReady={(mapProps, map) => {
                        this.setState({ map: map as google.maps.Map})
                    }}
                     style={mapStyle}
                     onClick={this.onMapClicked}>
                
                    <Marker onClick={this.onMarkerClick}
                            title={`Location of ...`} />
                    <InfoWindow google={google}
                                map={this.map as google.maps.Map}
                                marker={this.marker}
                                visible>
                        <div>
                            <h1>Hello.</h1>
                        </div>

                    </InfoWindow>
                </Map>
                <p className="float-left md:ml-32 mt-64 sm:pt-32 lg:pt-32">
                </p>
            </>
        )
    }
}

const GoogleMap = GoogleApiWrapper({
        apiKey: 'A------w'
    })(MapContainer)


export default GoogleMap;

基本上,我不知道如何使用MapContainer / GoogleMaps来获取道具,因此我在此类中使用axios将状态设置为纬度和经度。我在另一个文件夹中确实具有相同的经度和纬度,因此这是我的一种选择,但是我现在不介意这样做。但是,坐标保持在(0,0)。我是在混淆执行此操作的顺序还是什么?

编辑:顺便说一句,即使其他州也不会更新地图本身也不会更新

1 个答案:

答案 0 :(得分:1)

这是因为setState是异步的。因此setState之后的使用状态可能不会被更新。 您必须对setState使用回调函数以获取更新的值。 另外,您可以使用componentDidUpdate使用更新后的状态值。

所以您必须这样做:

this.setState(
    {
        latitude: Number(resp.data.location.latitude),
        longitude: Number(resp.data.location.longitude),
    },
    () => {
        console.log("Before:" + this.state.latitude + " and " + this.state.longitude);
    }
);