作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个网络应用程序,它允许您输入地址并呈现 map ,其中包含从给定地址到其他 4 个(目前为硬编码)地址的方向。一切正常,直到我想输入一个新地址并刷新 map
我正在使用 tomchentw/react-google-maps 库来获取方向并渲染 map
这是我的代码:
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'));
加载后,用户只会看到呈现的组件。输入地址并提交表单后, map 会正确显示。但是,当我输入新地址并重新提交表单时, map 不会重新呈现。
有什么我想念的吗?
最佳答案
您可能正在寻找函数 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();
}
}
关于ReactJS 谷歌地图组件不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670091/
leaflet:一个开源并且对移动端友好的交互式地图 JavaScript 库 中文文档: https://leafletjs.cn/reference.html 官网(英文): ht
我是一名优秀的程序员,十分优秀!