我正在编写一个网络应用程序,允许您输入一个地址并使用指定地址的指示呈现地图到另外4个(现在是硬编码)地址。一切正常,直到我想输入一个新地址并刷新地图
我正在使用tomchentw / react-google-maps库来获取路线并渲染地图
这是我的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { compose, withProps, withPropsOnChange, withState, lifecycle } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
DirectionsRenderer,
} from "react-google-maps";
const MapWithADirectionsRenderer = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `500px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
this.setState({
newDirections: [],
});
let destinations = ['Imperial College', '123 Aldersgate Street', '17 Moorgate', 'Spitafields Market']
const DirectionsService = new google.maps.DirectionsService();
DirectionsService.route({
origin: this.props.origin,
destination: destinations[0],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
DirectionsService.route({
origin: this.props.origin,
destination: destinations[1],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions1: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
DirectionsService.route({
origin: this.props.origin,
destination: destinations[2],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions2: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
DirectionsService.route({
origin: this.props.origin,
destination: destinations[3],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions3: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
}
})
)(props =>
<GoogleMap
defaultZoom={7}
defaultCenter={new google.maps.LatLng(51.435341, -0.131116)}
>
{props.directions && <DirectionsRenderer directions={props.newDirections[0]} />}
{props.directions1 && <DirectionsRenderer directions={props.newDirections[1]} />}
{props.directions2 && <DirectionsRenderer directions={props.newDirections[2]} />}
{props.directions3 && <DirectionsRenderer directions={props.newDirections[3]} />}
</GoogleMap>
);
class AddressForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
let targetAddress = this.state.value;
ReactDOM.render(<MapWithADirectionsRenderer origin={targetAddress} destination='Imperial College' />, document.getElementById('mapplace'));
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Address:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="submit" />
</form>
);
}
}
registerServiceWorker();
ReactDOM.render(<AddressForm />, document.getElementById('formplace'));
加载后,用户只能看到渲染的组件。输入地址并提交表单后,地图将正确显示。但是,当我输入新地址并重新提交表单时,地图不会重新呈现。
我有什么遗失的吗?
答案 0 :(得分:1)
您可能正在寻找在发生任何更新后运行的函数componentDidUpdate
,componentDidMount
只会在第一次渲染后调用一次。
我会提出以下更改清单:
a)引入一个单独的函数来绘制路线:
drawRoutes() {
let destinations = ['Imperial College', '123 Aldersgate Street', '17 Moorgate', 'Spitafields Market']
const DirectionsService = new google.maps.DirectionsService();
DirectionsService.route({
origin: this.props.origin,
destination: destinations[0],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
DirectionsService.route({
origin: this.props.origin,
destination: destinations[1],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions1: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
DirectionsService.route({
origin: this.props.origin,
destination: destinations[2],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions2: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
DirectionsService.route({
origin: this.props.origin,
destination: destinations[3],
travelMode: google.maps.TravelMode.TRANSIT,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions3: result,
newDirections: this.state.newDirections.concat([result])
});
} else {
console.error(`error fetching directions ${result}`);
}
});
}
b)设置初始状态:
componentWillMount() {
this.setState({
newDirections: [],
});
}
c)画出路线:
componentDidMount() {
this.drawRoutes();
}
d)如果地址已更改,则重绘路线
componentDidUpdate(prevProps, prevState) {
if (prevProps.origin !== this.props.origin) {
this.setState({
directions: null,
directions1: null,
directions2: null,
directions3: null,
newDirections: []
});
this.drawRoutes();
}
}