我一直绞尽脑汁想要解决问题。基本上,我希望状态中的markersList属性在呈现组件之前更新。 markerList假设使用在initMap()方法中推入数组的Google Maps标记填充。但是当我在render方法中控制数组时,数组为空。在渲染方法完成之前,我只需要帮助了解如何使用所有标记更新数组。我希望我提出的问题有道理。谢谢你们!
class App extends Component {
constructor(props) {
super(props);
this.state = {
map: "",
marker: "",
markersList: [],
locations: [
{
title: "Powell's Books",
address: "1005 W Burnside St, Portland, OR 97209",
coordinates: {
lat: 45.523096,
lng: -122.681354
}
},
{
title: "Ground Kontrol",
address: "511 NW Couch St, Portland, OR 97209",
coordinates: {
lat: 45.523943,
lng: -122.675872
}
},
{
title: "Portland Art Museum",
address: "1219 SW Park Ave, Portland, OR 97205",
coordinates: {
lat: 45.51615,
lng: -122.683357
}
},
{
title: "Roseland Theater",
address: "8 NW 6th Ave, Portland, OR 97209",
coordinates: {
lat: 45.52328,
lng: -122.676297
}
},
{
title: "Voodoo Doughnuts",
address: "22 SW 3rd Ave, Portland, OR 97204",
coordinates: {
lat: 45.522713,
lng: -122.672944
}
},
{
title: "Arlene Schnitzer Concert Hall",
address: "1037 SW Broadway, Portland, OR 97205",
coordinates: {
lat: 45.517197,
lng: -122.681419
}
},
{
title: "Pioneer Place",
address: "700 SW 5th Ave, Portland, OR 97204",
coordinates: {
lat: 45.518335,
lng: -122.677261
}
}
]
}
}
componentDidMount() {
this.initMap();
}
initMap = () => {
const map = document.querySelector(".map");
let newMap = new window.google.maps.Map(map, {
center: {
lat: 45.519692,
lng: -122.680496,
mapTypeControl: false
},
zoom: 16
});
let infoWindow = new window.google.maps.InfoWindow();
let locations = this.state.locations;
let bounds = new window.google.maps.LatLngBounds();
for (let i = 0; i < locations.length; i++) {
let wikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=" + this.state.locations[i].title + "&format=json";
let newMarker = new window.google.maps.Marker({
map: newMap,
position: locations[i].coordinates,
title: locations[i].title,
animation: window.google.maps.Animation.DROP
});
this.state.markersList.push(newMarker);
bounds.extend(newMarker.position);
newMarker.addListener("click", function () {
infoWindow.open(map, this);
newMap.panTo(newMarker.position);
axios.get(wikiUrl)
.then(response => {
const wikiInfo = response.data;
infoWindow.setContent(`<p><strong>${wikiInfo[0]}</strong><br>${locations[i].address}</p><p>${wikiInfo[2][0]}</p><p>Click <a href='${wikiInfo[3][0]}' target='_blank'><strong>HERE</strong></a> for more information on ${wikiInfo[0]}.</p>`)
})
})
}
newMap.fitBounds(bounds);
}
render() {
return (
<div>
<div className="menu">
<SearchInput />
<ul className="location-list" >
{console.log(this.state.markersList)}
{
}
</ul>
</div>
<div className="map">
</div>
</div>
);
}
}
答案 0 :(得分:2)
您是否尝试过调用componentWillMount
而不是componentDidMount
?