【发布时间】: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