我已经创建了一个具有Map.js组件的react应用,其代码如下所示。我能够使用ReactMapGL和Geocoder组件来创建MapboxGL地图,并且Popup组件运行良好。但是,我想让Apollo在用户单击地图时触发对GraphQL API端点的突变。下面的代码可以正常工作,并在Mutation组件中使用“ onClick = {createLocation}”触发了一个突变,但是它使用了在默认状态userLocation中定义的旧的默认经度和纬度变量。当用户点击地图时,我想触发handleViewportClick(设置点击点的经度和纬度,并输入到Popup组件中),并使用点击事件的经度和纬度来运行Mutation。
关于如何单击的任何建议如何使用单击的事件坐标运行突变并运行handleViewportportClick以更新userLocation的经度和纬度?
import React, { Component } from "react";
import ReactMapGL, { Marker, Popup } from "react-map-gl";
import Geocoder from 'react-map-gl-geocoder'
import gql from "graphql-tag";
import { Mutation } from "react-apollo";
import 'mapbox-gl/dist/mapbox-gl.css'
import 'react-map-gl-geocoder/dist/mapbox-gl-geocoder.css'
const MAPBOX_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const CREATE_LOCATION_MUTATION = gql`
mutation CreateLocation($name: String!, $latitude: Float!, $longitude: Float!) {
createLocation(name: $name, latitude: $latitude, longitude: $longitude) {
name
longitude
latitude
}
}
`;
class Map extends Component {
state = {
viewport: {
width: 400,
height: 400,
latitude: 37.7577,
longitude: -122.4376,
zoom: 8
},
userLocation: {
name: "DEFAULT_NAME",
latitude: 37.7577,
longitude: -122.4376
}
};
mapRef = React.createRef()
handleViewportChange = (viewport) => {
this.setState({
viewport: { ...this.state.viewport, ...viewport }
})
}
handleViewportClick = (event) => {
this.setState({
userLocation: {
name: "NEW_POINT,
latitude: event.lngLat[1],
longitude: event.lngLat[0]
}
});
}
handleGeocoderViewportChange = (viewport) => {
const geocoderDefaultOverrides = { transitionDuration: 1000 }
this.setState({
userLocation: {
latitude: viewport.latitude,
longitude: viewport.longitude
}
})
return this.handleViewportChange({
...viewport,
...geocoderDefaultOverrides
})
}
handleCompleted = data => {
};
handleUpdate = (cache, { data }) => {
};
render() {
return (
<Mutation
mutation={CREATE_LOCATION_MUTATION}
variables={this.state.userLocation}
onCompleted={this.handleCompleted}
update={this.handleUpdate}>
{(createLocation, { loading, error }) => {
return (
<div className="map_container">
<ReactMapGL
ref={this.mapRef}
{...this.state.viewport}
width="100vw"
height="700px"
mapStyle="mapbox://styles/mapbox/outdoors-v11"
onViewportChange={this.handleViewportChange}
onClick={createLocation}
mapboxApiAccessToken={MAPBOX_TOKEN}>
<Popup
latitude={this.state.userLocation.latitude}
longitude={this.state.userLocation.longitude}
closeButton={false}
closeOnClick={false}
anchor="top" >
<div>Test</div>
</Popup>
<Geocoder
mapRef={this.mapRef}
onViewportChange={this.handleGeocoderViewportChange}
mapboxApiAccessToken={MAPBOX_TOKEN}
zoom={10}
/>
</ReactMapGL>
</div>
)
}}
</Mutation>
);
}
}
export default Map;