【问题标题】:Axios does not update state immediatelyaxios 不会立即更新状态
【发布时间】:2020-07-17 20:01:55
【问题描述】:

我正在使用 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)。我是否混淆了执行此操作的顺序或其他内容?

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

【问题讨论】:

  • setState 是异步的,因此 setState 之后的 console.log 可能包含也可能不包含较新的值。状态更新后可以使用 setState 的回调函数对 console.log 的值进行回调

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


【解决方案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);
    }
);

【讨论】:

    猜你喜欢
    • 2021-11-07
    • 2018-08-05
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2018-08-12
    相关资源
    最近更新 更多