【问题标题】:Problem with rendering markers | React Native渲染标记问题 |反应原生
【发布时间】:2019-07-31 10:48:07
【问题描述】:

我在 react native-react-native-maps 中使用地图。

我需要将标记从 json 文件渲染到地图。

但是我有一个错误发生:

TypeError: TypeError: undefined is not an object (evaluating 'this.state.dataSource.map')

完整的代码块如下所示:

 {this.state.dataSource.map(item => (
 <Marker coordinate={item.latlng} />
   ))}

我从 json 文件中获取的标记的坐标,可能错误在这里?

"latlng": {
      "latitude": 53.6937,
      "longitude": -336.1968
    },

我需要你的帮助。完整代码:

export default class MapScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "Map",
      region: {
        latitude: 53.67,
        longitude: 23.83,
        latitudeDelta: 0.04,
        longitudeDelta: 0.09
      }
    };
  }

  componentDidMount() {
    return fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            dataSource: responseJson
          },
          function() {}
        );
      })
      .catch(error => {
        console.error(error);
      });
  }

  render() {
    const { title } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: "#1f1f1f" }}>
        <View style={styles.Header}>
          <HeaderProfile title={title} />
        </View>
        <MapView
          region={this.state.region}
          style={{ flex: 1 }}

        >
          {this.state.dataSource.map(item => (
            <Marker coordinate={item.latlng} />
          ))}
        </MapView>
      </View>
    );
  }
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您正在尝试在 undefined 上调用 map()。

    你有几个选择:

    1. 在状态中定义一个虚拟dataSource

      this.state = { 
        dataSource: [],
        ...
      
    2. 在调用map()之前检查是否定义了dataSource:

      {this.state.dataSource && this.state.dataSource.map...
      

    如果dataSource 是一个对象。 map() 仅适用于数组。您需要遍历对象:类似于

    Object.keys(dataSource).forEach(key => {
      return (<Marker coordinate={dataSource[key].latlan} />)
    });
    

    【讨论】:

    • 您好,感谢您的帮助。标记出现在地图上。但是有一个错误: Failed prop type: prop coordinateMapMarker 中标记为必填项,但其值为undefined
    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多