从后端获取Google Map的数据

时间:2019-06-17 13:22:13

标签: javascript json reactjs google-maps react-hooks

我在这里遵循此指南:https://youtu.be/Pf7g32CwX_s,介绍如何使用react-google-maps添加google map。 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返回数据,但是响应似乎太迟了。我收到此错误:

  

未捕获的TypeError:无法读取未定义的属性“ map”       在地图上(MapComponent.js:19)

在发生错误之前,控制台将输出:

  

MapComponent.js:14承诺{pending}

出现错误后,控制台将输出:

  

MapComponent.js:15 {type:“ FeatureCollection”,crs:{…},功能: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

2 个答案:

答案 0 :(得分:1)

是的,一旦标记被渲染,数据尚未加载。

更改列表:

a)像这样初始化默认值(以防止'map' of undefined error):

const [stationsData, setStationsData] = useState({ features: [] });

b)使用Effect Hook来获取数据:

useEffect(() => {
   fetchStationsData();
}, []);

其中

async function fetchStationsData() {
   const json = await stationsDataFunction();
   setStationsData(json);
}

示例

function Map(props) {
  const [data, setData] = useState([{ features: [] }]);

  async function fetchData() {
    const results = await fetch(
      "https://raw.githubusercontent.com/leighhalliday/google-maps-react-demo/master/src/data/skateboard-parks.json"
    );
    const json = await results.json();
    setData(json.features)
  }

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <GoogleMap defaultZoom={props.zoom} defaultCenter={props.center}>
      {data.map(item => (
        <Marker key={item.properties.PARK_ID} position={{
          lat: item.geometry.coordinates[1], 
          lng: item.geometry.coordinates[0]
        }} />
      ))}
    </GoogleMap>
  );
}

答案 1 :(得分:0)

您的代码中的问题是您在此处有一个异步调用

const stationsData = stationsDataFunction().then(response => {console.log(response); return response;});

但是当您尝试访问数据stationsData.features时,features是未定义的,因为承诺尚未解决。

您可以做的是连续的渲染

{stationsData.features && stationsData.features.map(...)}

但是,也许这不能解决您的问题,您将需要使用useEffect钩子。

import React, {useState, useEffect} from 'react';

function Map(){
    const [stationsData , setStationsData] = useState({}); 
    const [selectedStation, setSelectedStation] = useState(null); 

    useEffect(() => { 
        stationsDataFunction().then(response => {console.log(response); setStationsData(response);});
    }, [])

    return(
        <GoogleMap // Line 19
            defaultZoom={10}
            defaultCenter={{ lat: 63.0503, lng: 21.705826}}
        >
            {stationsData.features && stationsData.features.map(...)
        ...