首页 > 解决方案 > 反应原生地图:我无法为我的反应原生地图渲染标记?

问题描述

import React from 'react';
import { StyleSheet, Text, View, Component, Dimensions } from 'react-native';
import { fb } from "./Firebase/data";
import firestore from 'firebase/firestore';
import MapView, { Marker } from 'react-native-maps';

export default class App extends React.Component {

  state = {
      nodes: []
    }

  componentDidMount(){
        const db = fb.firestore()
          .collection('nodes')
          .get()
          .then( snapshot => {
            const nodes = []
            snapshot.forEach( doc =>{
              const data = doc.data()
              nodes.push(data)
            });
         this.setState({
          nodes : nodes
        })
      });
    }

    render() {
      console.log(this.state.nodes.lat)
      return (
        <MapView
        style={{ ...StyleSheet.absoluteFillObject }}
        initialRegion={{
          latitude: 28.5450,
          longitude: 77.1926,
          latitudeDelta: 0.0039922,
          longitudeDelta: 0.0039421,
        }} >

{this.state.nodes.map((marker, index) => {
      <Mapview.Marker 
        key = {index}
        coordinate = {{ latitude : marker.lat}, 
                      { longitude : marker.lon}}
        title = { marker.location }
        />
        } 
        )
      }

        </MapView>
      );
    }
}
console.disableYellowBox = true;
const styles = StyleSheet.create({
container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
  mapStyle: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
})

这是我的 react native 项目的父代码。如果需要,我还可以显示导出 fb 代码,但我相信它可以正常工作

有人可以告诉我这里出了什么问题,因为当我不调用 Mapview 时控制台上提供了来自 firebase 的数据,但就在我调用 Mapview 时,控制台显示 Array []。

我只想在地图上渲染标记

标签: reactjsreact-native

解决方案


您没有在地图上返回任何内容:

错了:this.state.nodes.map(()=>{})

真的 :this.state.nodes.map(()=>())

真正的 v2:this.state.nodes.map(()=>{ return ... })

最终代码应如下所示:

{this.state.nodes.map((marker, index) => (
  <Mapview.Marker
    key={index}
    coordinate={({ latitude: marker.lat }, { longitude: marker.lon })}
    title={marker.location}
  />
))}

推荐阅读