我有一个父组件和子组件。子项是以特定坐标为中心的 map 。在表单提交时,我通过传递来自父组件的 Prop (坐标)来更新子组件中的 map 坐标。坐标是根据用户输入的地址字符串进行地理编码的。
一切正常,只是响应虽然成功,但却无限循环。一分钟后,这会让我的浏览器崩溃。
我应该如何阻止响应每秒更新?
代码如下:
import React, { Component } from 'react';
import { Map, TileLayer } from 'react-leaflet';
import Geocode from "react-geocode";
class MapContainer extends Component {
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps) {
this.setState({centerMap: {
lat: nextProps.lat,
lng: nextProps.lng
}})
}
render() {
return (
<Map center={this.props.centerMap} zoom={13} >
<TileLayer
attribution="&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
);
}
}
class Card extends Component {
constructor(props) {
super(props);
this.state = {
userCoords: {
lat: 91.93373,
lng: -81.4280
}
}
}
render() {
let data = this.props.data;
// set Google Maps Geocoding API for purposes of quota management. Its optional but recommended.
Geocode.setApiKey("MY_API_KEY");
// Get latidude & longitude from address.
Geocode.fromAddress(data.location).then(
response => {
const coords = response.results[0].geometry.location;
this.setState({
userCoords: {
lat: coords.lat,
lng: coords.lng
}
})
},
error => {
console.error(error);
}
);
return (
<main className="main-card">
<div className="main-card--header-bg">
<MapContainer centerMap={this.state.userCoords}/>
</div>
</main>
);
}
}
export default Card;
最佳答案
移动
Geocode.setApiKey("MY_API_KEY");
到构造函数或全局。
然后创建一个方法说
fetchCoords(location) {
Geocode.fromAddress(location).then(
response => {
const coords = response.results[0].geometry.location;
this.setState({
userCoords: {
lat: coords.lat,
lng: coords.lng
}
})
},
error => {
console.error(error);
}
);
}
现在在Wrapper组件中写入componentDidMount和componentDidUpdate
componentDidMount() {
let data = this.props.data;
this.fetchCoords(data.location);
}
componentDidUpdate(prevProps) {
if(this.props.data != prevProps.data) {
let data = this.props.data;
this.fetchCoords(data.location);
}
}
componentDidMount 将获取坐标并将其设置为状态,从而触发重新渲染。所以 componentDidUpdate 将被调用,因为 props 没有改变,它不会再次调用 fetchCoords 。现在,如果 props.data 更改,将调用 componentDidUpdate,此时 props 将是新的,并且将启动新的获取。
关于javascript - React 组件成功后响应继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601488/