如何处理道具和状态以避免无限循环?

时间:2018-08-14 18:34:35

标签: javascript reactjs mapbox-gl-js

我有一个从父母那里获取道具的组件,我正在检查componentDidUpdate()中的this.props.addMarker是否为true,如果为true,它会触发其中存在setState的函数。

您可以想象下一步是什么:setState触发componentDidUpdate()函数,该函数检查this.props.addMarker是否为true ...等等...

该如何避免此类问题?

这是我的代码:

componentDidUpdate() {  
    if(this.props.addMarker) {
      const place = this.props.coordinatesToCenter;
      const coord = place.coordinates;

      this.addMarkerProcess(place.place_name, place.place_type, coord.lon, coord.lat);
    }
}

addMarkerProcess(name, maki, xCoordinate, yCoordinate) {
    const data = {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [xCoordinate, yCoordinate]
      },
      properties: {
        // place:
        // login:
        lat: yCoordinate,
        lon: xCoordinate,
        color: "#00FFFF"
      }
    };

    if(this.state.clickIsEmpty) {
      data.properties.place = this.state.userNewPlaceInput;
      data.properties.login = this.state.userNewTypeInput;
    } else {
      data.properties.place = name;
      data.properties.login = maki;
    }

    const prevGeoJson = _.cloneDeep(this.state.geoJson);
    console.log("prevGeojson1", prevGeoJson)
    // map only rerenders geoJSONLayer if geoJSONLayer.data is a new instance:
    const geoJson = Object.assign({}, this.state.geoJson);
    geoJson.features.push(data);

    this.setState(prevState => ({
      prevGeoJson: prevGeoJson,
      geoJson: geoJson,
      currentMarker: data
    }));

    let canvas = document.querySelector('.mapboxgl-canvas');
    if(canvas.classList.contains("cursor-pointer")) {
      canvas.classList.remove("cursor-pointer");
    }
  }

1 个答案:

答案 0 :(得分:2)

componentDidUpdate()在更新后立即被调用,因此,如果在不包装条件的情况下调用setState(),将不可避免地导致无限循环的发生。 您可以根据新setState()与旧props之间的比较来调用componentDidUpdate(prevProps) { if(this.props.data !== prevProps.data) this.fetchNewData(this.props.data); }

pickle