【发布时间】:2016-11-23 17:24:39
【问题描述】:
我正在尝试将 React 地图组件添加到我的项目中,但遇到了错误。我使用 Fullstack React 的 blog post 作为参考。我在 google_map.js 第 83 行追踪了错误发生的位置:
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
到目前为止,这是我的地图组件。当我注释掉最后三行第 58-60 行时,页面加载得很好(没有地图)。编辑:我做了@Dmitriy Nevzorov 建议的更改,但仍然给我同样的错误。
import React from 'react'
import GoogleApiComponent from 'google-map-react'
export class LocationsContainer extends React.Component {
constructor() {
super()
}
render() {
const style = {
width: '100vw',
height: '100vh'
}
return (
<div style={style}>
<Map google={this.props.google} />
</div>
)
}
}
export class Map extends React.Component {
componentDidUpdate(prevProps, prevState){
if (prevProps.google !== this.props.google){
this.loadMap();
}
}
componentDidMount(){
this.loadMap();
}
loadMap(){
if (this.props && this.props.google){
const {google} = this.props;
const maps = google.maps;
const mapRef = this.refs.map;
const node = ReactDOM.findDOMNode(mapRef);
let zoom = 14;
let lat = 37.774929
let lng = 122.419416
const center = new maps.LatLng(lat, lng);
const mapConfig = Object.assign({}, {
center: center,
zoom: zoom
})
this.map = new maps.Map(node, mapConfig)
}
}
render() {
return (
<div ref='map'>
Loading map...
</div>
)
}
}
export default GoogleApiComponent({
apiKey: MY_API_KEY
})(LocationsContainer)
这里是这个地图组件在 main.js 中被路由的地方:
import {render} from 'react-dom';
import React from 'react';
import Artists from './components/Artists'
import { Router, Route, Link, browserHistory } from 'react-router'
import Home from './components/HomePage'
import Gallery from './components/ArtGallery'
import ArtistPage from './components/ArtistPage'
import FavsPage from './components/FavsPage'
import LocationsContainer from './components/Locations'
//Create the route configuration
render((
<Router history={browserHistory}>
<Route path="/" component={Home} />
<Route path="locations" component={LocationsContainer} />
<Route path="artists" component={Artists} />
<Route path="gallery" component={Gallery} />
<Route path="favorites" component={FavsPage} />
<Route path=":artistName" component={ArtistPage} />
</Router>
), document.getElementById('app'))
【问题讨论】:
-
你有两个
export defaults,是new GoogleAPIComponent()而不是GoogleAPIComponent()? -
我删除了其中一项默认设置并尝试了您的建议。看起来它现在实际上正在与谷歌地图交谈,这很好,但在页面加载之前它会引发另一个神秘错误:Locations.js:58 Uncaught TypeError: (intermediate value) is not a function”。有什么想法吗?
-
如果删除
(LocationContainer)会怎样? -
谢谢,我想明白了!奇怪,这就是他们在博客文章上写的方式。仍然从 Google 地图中收到一些其他错误,我将它们放在这里:'GoogleMap: apiKey 已弃用,请改用 bootstrapURLKeys={{key: YOUR_API_KEY}}。 google_map.js:689 GoogleMap: center 或 defaultCenterproperty 必须定义 google_map.js:699 GoogleMap: zoom 或 defaultZoomproperty 必须定义 google_map.js: 704'
-
我不确定其他错误,但您可以尝试修复第一个错误:
export default new GoogleApiComponent({ bootstrapURLKeys: MY_API_KEY })
标签: javascript google-maps reactjs ecmascript-6 react-router