【发布时间】:2019-10-31 02:27:53
【问题描述】:
我在这里关注本指南:https://youtu.be/Pf7g32CwX_s,了解如何使用 react-google-maps 添加谷歌地图。 Github 上的代码:https://github.com/leighhalliday/google-maps-react-demo/blob/master/src/App.js
我已经启动并运行了示例,但现在我想从后端获取数据,而不是在前端使用 json 文件。所以我有这个设置:
App.js
import React from 'react';
export async function stationsDataFunction() {
const results = await fetch('http:...) ;
return results.json();
}
class App extends React.Component {
constructor(){
super();
this.state = {
}
}
render(){
return(
<div className="App">
<MapComponent/>
</div>
)
}
}
export default App;
MapComponent.js
import React, {useState} from 'react';
import { GoogleMap, Marker, withScriptjs, withGoogleMap, InfoWindow } from "react-google-maps"
import {stationsDataFunction} from './App';
function Map(){
console.log(stationsDataFunction()); // Line 14
const stationsData = stationsDataFunction().then(response => {console.log(response); return response;}); // Line 15
const [selectedStation, setSelectedStation] = useState(null);
return(
<GoogleMap // Line 19
defaultZoom={10}
defaultCenter={{ lat: 63.0503, lng: 21.705826}}
>
{stationsData.features.map(station => (
<Marker
key={station.properties.PARK_ID}
position={{
lat: station.geometry.coordinates[1],
lng: station.geometry.coordinates[0]
}}
onClick={(() => {
setSelectedStation(station);
})}
/>
))}
//... more code here
我正在将数据从后端返回到 const StationData,但似乎响应来得太晚了。我收到此错误:
未捕获的类型错误:无法读取未定义的属性“地图” 在地图 (MapComponent.js:19)
出现错误之前控制台打印出来:
MapComponent.js:14 承诺{待定}
出错后控制台打印出:
MapComponent.js:15 {type: "FeatureCollection", crs: {…}, features: Array(2)}
我不知道如何解决这个问题。
使用工作代码更新
App.js 工作代码
导出函数如下:
export async function stationsDataFunction() {
const results = await fetch('http://localhost:4000/api/myData/stationNames') ;
return results.json();
}
MapComponent.js 工作代码
import React, {useState, useEffect} from 'react';
import { GoogleMap, Marker, withScriptjs, withGoogleMap, InfoWindow } from "react-google-maps"
import {stationsDataFunction} from './App';
function Map(){
const [stationsData , setStationsData] = useState({ features: [] });
const [selectedStation, setSelectedStation] = useState(null);
async function fetchStationsData() {
const json = await stationsDataFunction();
setStationsData(json);
}
useEffect(() => {
fetchStationsData();
}, []);
return(
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: 63.0503, lng: 21.705826}}
>
{stationsData.features && stationsData.features.map(station => (
<Marker
key={station.properties.PARK_ID}
position={{
lat: station.geometry.coordinates[1],
lng: station.geometry.coordinates[0]
}}
// More code here
【问题讨论】:
标签: javascript json reactjs google-maps react-hooks