reactjs - React 限制嵌套更新的数量以防止无限循环
问题描述
我正在使用 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;
解决方案
这种情况下的错误是必须使用回调调用 onClick 事件,如果没有,则每次渲染都会不断实例化该函数,所以在这种情况下
onClick={()=>this.handleClick()}
当然,请阅读 React 网站的基本文档,因为您的代码充满了错误。
推荐阅读
- java - 在 Java 中使用 ASM 测试跳转
- css - 滑动移动导航溢出
- docker - 为什么 Neo4J docker 身份验证不起作用
- raku - 使用冒号语法的错误方法调用。没有错误。但是这是什么意思?
- css - 固定高度元素强制其他元素在 Firefox 上的高度为零
- amazon-dynamodb - 如何在 DynamoDB 中建模一对一、一对多和多对多关系
- java - 无法读取下一个控制台行 - NoSuchElementException
- javascript - 页面加载 jQuery 表单提交不起作用
- python - 使用 biopython 从 NCBI 获取基因组
- ios - 根据用户显示扩展