我正在使用React Google Maps将Google地图添加到我的页面,我在这里设置地图:
import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
export const MapWithMarkers = withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={17}
center={{ lat: parseFloat(props.lat), lng: parseFloat(props.long) }}
>
{props.markers.map(marker => (
<Marker
key={marker.todoId}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
/>
))}
</GoogleMap>
))
但是,我想使用this.props.store.lat
注入商店并使用props.lat
而不是@inject('store')
,这需要将MapWithMarkers转换为类而不是const。
我尝试了以下内容:
import React from "react";
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
@inject('store') @observer
export class MapWithMarkers extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
}
renderMarkers = (props) => {
<GoogleMap
defaultZoom={17}
center={{ lat: parseFloat(this.props.store.lat), lng: parseFloat(this.props.store.long) }}
>
{this.props.store.todos.map(marker => (
<Marker
key={marker.todoId}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
/>
))}
</GoogleMap>
}
render() {
const props = this.props;
return withScriptjs(withGoogleMap(this.renderMarkers()));
}
}
这不起作用,返回:
未捕获(承诺)错误:MapWithMarkers.render():A 必须返回有效的React元素(或null)。你可能已经回来了 undefined,数组或其他一些无效对象。
我做错了什么?
答案 0 :(得分:1)
withScriptjs
&amp; withGoogleMap
是HOC,您应该将HOC传递给组件。所以你的组件应该是这样的:
import React from "react";
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
@inject('store') @observer
export class Map extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
}
render() {
return <GoogleMap
defaultZoom={17}
center={{ lat: parseFloat(this.props.store.lat), lng: parseFloat(this.props.store.long) }}
>
{this.props.store.todos.map(marker => (
<Marker
key={marker.todoId}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
/>
))}
</GoogleMap>
}
}
export const MapWithMarkers = withScriptjs(withGoogleMap(Map))