javascript - 从后端获取谷歌地图的数据

标签 javascript json reactjs google-maps react-hooks

我在这里遵循本指南: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 stationsData,但似乎响应来得太晚了。我收到此错误:

Uncaught TypeError: Cannot read property 'map' of undefined at Map (MapComponent.js:19)

错误发生前控制台打印出:

MapComponent.js:14 Promise {pending}

错误发生后控制台打印出:

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

最佳答案

没错,一旦标记被渲染,数据还没有加载。

变化列表:

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>
  );
}

关于javascript - 从后端获取谷歌地图的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56632248/

相关文章:

javascript - 按钮工具提示上的数据标题未更新

ios - 在 Array of Dictionaries of array 中搜索一个值

json - 如何在 swift 中使用 Object Mapper 将 JSON String 映射到模型类

javascript - 使用 angularjs 将数据添加到 json-ld

javascript - 单击导航项时关闭导航

Javascript:使用 while 循环在给定的计数参数中重复一个字符串

javascript - json 数组内的数组

javascript - 解析 JSON 后, bool 值未显示在组件中

css - 在 react 中呈现嵌套表行

javascript - 如何在(Ant-design)中更改步骤颜色