componentDidUpdate prevProps 给我当前/新的道具

Mar*_*rco 8 leaflet reactjs

我正在尝试集成传单地图,但我认为这不是问题所在。无论如何要重新渲染我的地图,我想使用 componentDidUpdate 来查看道具是否发生变化,我从父组件传递给我的地图组件。但是现在问题来了,每当我尝试console.log(prevProps.xx, this.props.xx)它们时它们都是完全相同的,即使我刚刚更新它,所以我不能真正使用 componentDidUpdate,还有其他方法吗?此外 componentWillReceiveProps 将不起作用,当我在父组件更新我的状态并将其传递给我的地图组件时,它总是 1:1 相同,因此无法进行比较。

这是我的代码:

var Map = React.createClass({

map: null,
tileLayer : null,

componentDidMount: function() {
   // code to run just after the component "mounts" / DOM elements are created
   // make the AJAX request for the GeoJSON data
   // create the Leaflet map object
   if (!this.map) this.init('mapid');
 },
 componentWillReceiveProps: function(nextProps) {
   console.log(nextProps.labels, this.props.labels);
 },
 componentDidUpdate(prevProps, prevState) {
   const zoom = this.props.labels.zoom;
   const mapstyle = this.props.labels.mapstyle;
   const latlng = [this.props.labels.lat, this.props.labels.lng];
   this.map.setView(latlng);
   this.tileLayer.setUrl(mapstyle);
   console.log(prevProps.labels, this.props.labels);
  },

 init: function(id) {
  const zoom = this.props.labels.zoom;
  const mapstyle = this.props.labels.mapstyle;
  const latlng = [this.props.labels.lat, this.props.labels.lng];
  if (this.map) return;
  // this function creates the Leaflet map object and is called after the Map component mounts
  this.map = L.map(id).setView(latlng,zoom);


  // a TileLayer is used as the "basemap"
  this.tileLayer = L.tileLayer(mapstyle).addTo(this.map);

  // set our state to include the tile layer
  },
  render: function(){
    return(
      <div></div>
    )
  },

  });
Run Code Online (Sandbox Code Playgroud)

小智 -2

  1. 创建一个新的状态元素,比方说response
  2. 将道具分配给response
  3. 尝试在里面写函数render()