【发布时间】:2020-05-20 01:12:41
【问题描述】:
我正在使用 react js 在地图上显示位置。并从 json 文件中获取坐标。 I set up a button to select each.then when the coords are selected I have to rerender to display new info I've just got.但我有一个错误说: 错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制嵌套更新的数量以防止无限循环
const data = UserParents.all.children;
class App extends Component{
state = {
greenIcon : {
lat: 51.505,
lng: -0.09,
},
zoom: 13,
}
greenIcon = L.icon({
iconUrl : leafGreen ,
shadowUrl : leafShadow ,
iconSize: [38, 95],
shadowSize: [50, 64],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76]
});
handleClick (userId) {
if (userId == 3966){
this.state.greenIcon.lat = User3966.coords[0].lat;
this.state.greenIcon.lng = User3966.coords[0].lng;
}else if (userId == 3967) {
this.state.greenIcon.lat = User3967.coords[0].lat;
this.state.greenIcon.lng = User3967.coords[0].lng;
}else if (userId == 3968) {
this.state.greenIcon.lat = User3968.coords[0].lat;
this.state.greenIcon.lng = User3968.coords[0].lng;
}else if (userId == 3969) {
this.state.greenIcon.lat = User3969.coords[0].lat;
this.state.greenIcon.lng = User3969.coords[0].lng;
}else if (userId == 3970) {
this.state.greenIcon.lat = User3970.coords[0].lat;
this.state.greenIcon.lng = User3970.coords[0].lng;
}
this.forceUpdate();
}
render() {
const positionGreenIcon = [this.state.greenIcon.lat, this.state.greenIcon.lng]
return (
<div className="App">
<div>
{
Object.keys(data).map((key)=>(
<div>
<h4>{data[key].name}</h4>
<h4>{key}</h4>
<button onClick={this.handleClick()}>Select</button>
<br/>
<br/>
<br/>
</div>
))
}
</div>
<Map className='map' center={positionGreenIcon} zoom={this.state.zoom} >
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={positionGreenIcon} icon={this.greenIcon}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</Map>
</div>
);
}
}
export default App;
【问题讨论】:
-
删除
this.forceUpdate() -
但是如何重新渲染?
-
首先,请仔细阅读官方文档的基本概念,您对
props和state的更改会导致自动重新渲染。而且,你永远不能通过直接给它赋值来设置state,而是使用this.setState({ XXX: value })。