【问题标题】:i can fetch data from google map api but I can't update state with the data我可以从谷歌地图 api 获取数据,但我不能用数据更新状态
【发布时间】:2018-10-08 02:01:16
【问题描述】:

我正在尝试从 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;

【问题讨论】:

  • this.setState 将在收到 API 响应之前被调用。所以 geoData 将为空 Object {}。

标签: javascript reactjs google-maps


【解决方案1】:

简短的回答是 - 状态不会随着获取请求的响应而更新。

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

在上面的源代码中,setState 是在 promise 之外调用的(在 componentDidMount 方法中),本质上是异步的 promise 不会在你调用然后触发 promise 时完成,解释器会继续使用 geodata={} 调用 setState。

希望您现在了解.then(()=&gt;{}) 的实用性。确保 Promise 成功后某些代码的执行。

还有一个指针,当你想访问状态时使用this.state,因为它是实例属性,this 用于访问类内部的这些属性。

因此,带有回调的正确 setState 调用应该如下所示 - this.setState({geolocation: geodata}, ()=&gt;{console.log(this.state)})

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多