我正在使用react-google-maps显示经纬度数据中的标记。这可以正常工作,但是每次更新标记数据时,整个组件都会渲染。有没有办法只更新标记?我的代码如下。数据输入很快,所以我只让它每10秒更新一次。我要同时更新标记和中心。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions';
import { compose, withProps } from 'recompose';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
import globalStyles from '../App.css';
import styles from '../styles/ViewMap.module.scss';
class ViewMap extends Component {
constructor() {
super();
this.state = {
lat: 0,
long: 0,
updateMap: true
};
}
shouldComponentUpdate(nextProps, nextState) {
if(this.state.updateMap){
return true;
}
else {
return false;
}
}
componentWillUpdate() {
if (this.state.updateMap) {
for (var key in this.props.vehicleAggregateData.vehiclesData) {
if (key === this.props.vin) {
let latitude = this.props.vehicleAggregateData.vehiclesData[key].position[0];
let longitude = this.props.vehicleAggregateData.vehiclesData[key].position[1];
var self = this;
window.setTimeout(function(){
self.setState({ updateMap: true, lat: latitude, long: longitude });
}, 10000);
self.setState({ updateMap: false});
}
}
}
else{
return false;
}
}
render() {
const MyMapComponent = compose(
withProps({
googleMapURL:
'https://maps.googleapis.com/maps/api/js?key=AIzaSyBitA9VEk3r2trmEW-xXTh_8YDpcIfBwy4&v=3.exp&libraries=geometry,drawing,places',
loadingElement: <div className={globalStyles.paperCard} />,
containerElement: <div style={{ height: '100%' }} />,
mapElement: <div style={{ height: '100%' }} />
// key:"AIzaSyBitA9VEk3r2trmEW-xXTh_8YDpcIfBwy4"
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={18} defaultCenter={{ lat: parseFloat(this.state.lat), lng: parseFloat(this.state.long) }}>
{props.isMarkerShown && <Marker position={{ lat: parseFloat(this.state.lat), lng: parseFloat(this.state.long) }} />}
</GoogleMap>
));
return (
<div className={styles.map + " " + globalStyles.cardShadow}>
<MyMapComponent isMarkerShown />
</div>
);
}
}
function mapStateToProps(state) {
return {
vehicleAggregateData: state.vehicleData
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ViewMap);