2016-09-23 72 views
-1

我該如何解決這個錯誤?我該如何解決「Uncaught TypeError:無法讀取未定義的屬性'map'?

SimpleMap.js:35, Uncaught TypeError: Cannot read property 'map' of undefined

import React from "react"; 
    import {GoogleMapLoader, GoogleMap, Marker} from "react-google-  maps"; 

    export default function SimpleMap (props) { 

    var markers = [{ 
     position: 
     { lat: -34.397, lng: 150.644 } 
     , 
     index: "1" 
    }]; 
return (

    <section style={{height: "100%"}}> 
     <GoogleMapLoader 
      query={{ libraries: "geometry,drawing,places,visualization" }} 
      containerElement={ 
     <div 
     {...props.containerElementProps} 
     style={{ 
      height: "100%", 
     }} 
     /> 

    } 


      googleMapElement={ 
     <GoogleMap 
     ref={(map) => console.log(map)} 
     defaultZoom={3} 
     defaultCenter={{ lat: -25.363882, lng: 131.044922 }} 
     onClick={props.onMapClick} 
     > 
     {props.markers.map((marker) => { 
      return (
      <Marker 
       {...marker} 
       onRightclick={() => props.onMarkerRightclick(index)} /> 
     ); 
     })} 
     </GoogleMap> 
    } 
      ></GoogleMapLoader> 
    </section> 
); 

} 
+0

'props.markers'在第35行未定義。 –

+0

將第6行從'var markers ='更改爲'props.markers ='並查看是否有幫助。 –

+0

它給出了這個錯誤。 SimpleMap.js:6 Uncaught TypeError:不能添加屬性標記,對象不可擴展。 –

回答

0

這真的很難說是什麼問題。您的代碼中存在很多錯誤,並且我無法從您發佈的代碼段中看到整個圖片。真的,你將不得不學習如何調試JavaScript錯誤,直到你可以跟蹤它們。這是很多工作,但我不能爲你做。爲了給你一些指導,理想情況下你的代碼應該看起來更像這樣;

import React, {Component} from 'react'; 
import {GoogleMapLoader, GoogleMap, Marker} from "react-google-maps"; 

export default class SimpleMap extends Component { 
    var { markers, containerElementProps, onMapClick, onMarkerRightClick } = this.props; 
    markers = [{ 
    position: { lat: -34.397, lng: 150.644 }, 
    index: "1" 
    }]; 
    var containerEl = <div {...containerElementProps} />; 
    var mapEl = <GoogleMap 
    defaultZoom={3} 
    defaultCenter={{ lat: -25.363882, lng: 131.044922 }} 
    onClick={onMapClick} 
    > 
    {markers.map((marker) => { 
     return (<Marker {...marker} onRightclick={onMarkerRightClick} />); 
    })} 
    </GoogleMap>; 
    return (
    <section> 
     <GoogleMapLoader 
     query={{ libraries: "geometry,drawing,places,visualization" }} 
     containerElement={containerEl} 
     googleMapElement={mapEL} 
     /> 
    </section> 
); 
} 

然後像這樣使用該組件;

import { SimpleMap } from './path/to/component'; 
... 
// Inside your render function 
<SimpleMap markers={yourMarkers} containerElementProps={this.props} onMapClick={yourOnMapClickFunction} onMarkerRightClick={yourOnMarkerRightClickFunction} /> 

但是不要複製和粘貼該代碼,因爲它不起作用。它沒有經過測試,我沒有看到你的項目的全貌,我寫了它。這只是一個模糊的想法,但它應該讓你繼續下去。

+0

感謝您的提示,將在此工作。 –