首页 > 解决方案 > 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='&amp;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;

标签: reactjsleafletrerender

解决方案


这种情况下的错误是必须使用回调调用 onClick 事件,如果没有,则每次渲染都会不断实例化该函数,所以在这种情况下

onClick={()=>this.handleClick()}

当然,请阅读 React 网站的基本文档,因为您的代码充满了错误。


推荐阅读