如何从withHandlers调用另一个函数?

时间:2019-05-15 08:45:39

标签: reactjs react-google-maps recompose

我正在尝试使用react-google-maps包在我的应用中实现google maps。在地图中,我显示了多个Marker,并使用了MarkerCluster

直到现在我都没有问题,并且可以从文档轻松实现。但是,现在我想显示InfoWindow,如果单击了标记。

因此,我想到了一个函数来获取click事件并传递markerId,因此我可以调用API并获取该标记的相关数据,然后以表格的形式将其放入信息窗口。

现在,我面临的问题是:

1)从onToggleOpen呼叫onMarkerClick

2)如何在onMarkerClick的infowindow对象中设置数据

我面临的所有这些问题是因为我正在使用HOC,即recompose。 我习惯于使用Class实现,但是尝试过使用功能实现,使其完全无状态。

参考链接:https://tomchentw.github.io/react-google-maps/#infowindow

以下是我的代码:

import React, { Component } from "react";
import Header from "./Header.js";
import Sidebar from "./Sidebar.js";
import axios from "axios";
import imgmapcluster from "./pins/iconmapcluster.png";
import user from "./pins/user1copy.png";
import { compose, withProps, withHandlers } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} from "react-google-maps";
// const fetch = require("isomorphic-fetch");
const {
  MarkerClusterer
} = require("react-google-maps/lib/components/addons/MarkerClusterer");

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=AIzaSyCHi5ryWgN1FcZI-Hmqw3AdxJQmpopYJGk&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `90vh` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withHandlers(
    {
      onMarkerClustererClick: () => markerClusterer => {
        // console.log("markerCluster", markerClusterer);
        const clickedMarkers = markerClusterer.getMarkers();
        // console.log(`Current clicked markers length: ${clickedMarkers.length}`);
        // console.log(clickedMarkers);
      },
      onMarkerClick: (props) => markerss => {


        //calling api and setting info window object
         props.isOpen=!props.isOpen //showing error 

      },
      onToggleOpen: ({ isOpen }) => () => ({
        isOpen: !isOpen
      })
    }
  ),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultZoom={5}
    defaultCenter={{ lat: 22.845625996700075, lng: 78.9629 }}
    >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      averageCenter
      styles={[
        {
          textColor: 'white',
          url: imgmapcluster,
          height: 68,
          lineHeight: 3,
          width: 70
        }

      ]}
      enableRetinaIcons
      gridSize={50}
    >
      {props.markers.map((marker, index) => (
        <Marker
          key={index}
          icon={user}
          onClick={props.onMarkerClick.bind(props,marker)}
          position={{ lat: marker.latitude, lng: marker.longitude }}
        />
      ))}
      {props.isOpen && (
        <InfoWindow
          // position={{ lat: props.infowindow.lat, lng: props.infowindow.lng }}
          onCloseClick={props.onToggleOpen}
        >
          <h4>hello</h4>
        </InfoWindow>
      )}
    </MarkerClusterer>
  </GoogleMap>
));

class DemoApp extends React.PureComponent {
  componentWillMount() {
    this.setState({ markers: [],isOpen:false,infowindow:{} });
  }

  componentDidMount() {

    axios({
      url: "http://staging.clarolabs.in:6067/farmerinfo/farmercoordinates",
      method: "POST",
      data: {
        temp: "temp"
      },
      headers: {
        "Content-Type": "application/json"
      }
    }).then(res => {

      this.setState({ markers: res.data.data.list });
    });

  }

  render() {
    return <MapWithAMarkerClusterer markers={this.state.markers} isOpen={this.state.isOpen} InfoWindowobject={this.state.InfoWindowobject}/>;
  }
}

2 个答案:

答案 0 :(得分:2)

为了从另一个调用withHandler,您需要在两个处理程序中将它们分开。您还可以使用withStateHandler并存储infoWindow状态

withStateHandlers(
    { infoWindow: null },
    {
      setInfoWindow: () => (value) => ({ infoWindow: value)
    }
),
withHandlers({
  onToggleOpen: ({ isOpen }) => () => ({
        isOpen: !isOpen
  })
}),
withHandlers(
    {
      onMarkerClustererClick: () => markerClusterer => {
        // console.log("markerCluster", markerClusterer);
        const clickedMarkers = markerClusterer.getMarkers();
        // console.log(`Current clicked markers length: ${clickedMarkers.length}`);
        // console.log(clickedMarkers);
      },
      onMarkerClick: (props) => markerss => {
        const { setInfoWindow, onToggleOpen} = props;

        //calling api and setting info window object
        setInfoWindow({lat: res.lat, lng: res.lng}) // set infoWindow object here
        onToggleOpen() // Toggle open state


      }
    }
  ),

答案 1 :(得分:0)

您可能应该使用withStateHandlers来处理状态。另外,您可以多次写入withHandlers,因此withHandlers之后的处理程序将有权访问其他处理程序。

compose(
  // .....
  withStateHandlers(
    { isOpen: false },
    {
      toggleOpen: (state) => () => ({ isOpen: !state.isOpen }),
      // or
      setOpen: () => (value) => ({ isOpen: value }),
    }
  ),
  withHandlers(
    // .....
    {
      onMarkerClick: (props) => markerss => {
       // .....
       props.toggleOpen();
       // .....
      },
    },
    // .....
  ),
  // .....
)