繁体   English   中英

我可以从Google Map API获取数据,但无法使用数据更新状态

[英]i can fetch data from google map api but I can't update state with the data

我正在尝试从Google API获取地理代码,将其保存为状态,然后将其传递给GoogleMap组件。 我正确地将地理代码作为对象(例如{lat:37.5397407,lng:126.9895666})。但是,该状态未更新,也没有执行“ console.log(this.state)”。 我做错什么了吗?

import React from "react";
import PeopleInfoStyle from "../../../styles/presentational/PeopleInfoStyle";
import Carousel from "../../containers/Carousel/Carousel";
import GoogleMap from "../../presentational/GoogleMap/GoogleMap";

class PeopleInfo extends React.Component {
  state = {};

  componentDidMount() {
    let geoData = {};
    fetch(
      `https://maps.googleapis.com/maps/api/geocode/json?address=${
        this.props.person.address
      }&key="SECRET_KEY`
    )
      .then(res => res.json())
      .then(data => {
        geoData = data.results[0].geometry.location;
        console.log(geoData); // {lat: 37.5397407, lng: 126.9895666}
      })
      .catch(err => console.log(err));
    this.setState({ geoLocation: geoData }, ()=>{console.log(state)});
  }
  render() {
    const person = this.props.person;
    const images = [
      <img key={0} alt="" src={person.imgURL} />,
      ...person.subImgURLs.map((url, index) => {
        return <img alt="" src={url} key={index + 1} />;
      })
    ];

    return (
      <PeopleInfoStyle>
        <Carousel>{images}</Carousel>
            {!this.state.getLocation ? null : (
                <GoogleMap
                  id="map"
                  option={{
                    center: {
                      lat: this.state.geoLocation.lat,
                      lng: this.state.geoLocation.lng
                    },
                    zoom: 8
                  }}
                  onMapLoad={map => {
                    const market = new window.google.maps.Marker({
                      position: {
                        lat: this.state.geoLocation.lat,
                        lng: this.state.geoLocation.lng
                      },
                      map: map,
                      title: "business"
                    });
                  }}
                />
        </PeopleInfoStyle>
    );
  }
}

export default PeopleInfo;

简短的答案是-状态不会根据获取请求的响应进行更新。

一旦api请求完成,即在“ then”回调之一内,必须更新状态。

就像上面的源代码中一样,setState在promise之外被调用(在componentDidMount方法中),本质上异步的promise不会在您进行调用然后触发promise时完成,解释器将继续调用setState使用geodata={}

希望您现在了解.then(()=>{})的实用程序。 这些保证了Promise成功之后某些代码的执行。

还有一个指针,当你要访问的国家使用this.state ,因为它是实例属性而this被用来访问类中的属性。

因此,具有回调的正确setState调用应如下所示this.setState({geolocation: geodata}, ()=>{console.log(this.state)})

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM