0

我正在使用React Google Maps将 Google Maps 添加到我的页面,并在此处设置地图:

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>
))

但是,我想注入一个 store 和 usethis.props.store.lat而不是props.latusing @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():必须返回有效的 React 元素(或 null)。您可能返回了未定义、数组或其他一些无效对象。

我究竟做错了什么?

4

1 回答 1

0

withScriptjs&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))
于 2018-01-29T05:06:15.260 回答