【问题标题】:react leaflet not showing updated state反应传单未显示更新状态
【发布时间】:2021-12-02 00:26:21
【问题描述】:

我正在从我的设备存储中获取数据并希望在地图上显示数据。但是当我在函数showPics() 中更新我的状态对象this.coords.path 时,只显示{lat:1,lng:1} 处的测试标记,所有其他坐标都被推送到this.coords.path 但不显示...

我已经尝试使用 sampleData-array 来测试基本代码 -> 循环并且一切正常 - 只是在使用新数据更新状态对象时不行......

代码如下:

class Map extends React.Component {

    constructor(props) {
      super(props);
      this.coords = {
        path: [
            {lat:1, lng:1}
        ]
      }
    }      
  
    showPics = async() => {

        let {value} = await Storage.get({key: 'path' })
        let arrayPath = JSON.parse(value)

        for( let i=0; i < arrayPath.length; i++) {

            let newArray = {lat: arrayPath[i].latitude, lng: arrayPath[i].longitude}
            this.coords.path.push(newArray)

        }

    }
  
    render() {
  
      const sampleData = [{
        "Id": 1,
        "lat": 54.083336,
        "lng: 12.108811
      },
      {
        "Id": 2,
        "lat": 54.084336,
        "lng": 12.109811
      }]
      
      return (
        <div className="leaflet-container">
          <MapContainer id="map" center={center} zoom={zoom} scrollWheelZoom={false}>          
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
  
            { this.coords.path.map(eachData => (
           <Marker
             position= {[eachData.lat, eachData.lng]}
           />
         ))}

          <IonFab vertical="bottom" horizontal="end" slot="fixed">
            <IonFabButton onClick={() => this.showPics()}>
              <IonIcon icon={image}></IonIcon>
            </IonFabButton>
          </IonFab>
        </div>
      )
  
    }
  }

【问题讨论】:

    标签: javascript reactjs ionic-framework leaflet


    【解决方案1】:

    您正在尝试将数据设置为this.coords。这不会被 react 跟踪,并且无法更新 DOM。相反,您可以将数据设置为组件状态,如下所示

    state = {
       coords: {
        path: [
            {lat:1, lng:1}
        ]
      }
    }
    

    函数showPics可以修改如下,将数据设置为使用setState的状态,该状态应由virtualDOM选择并相应更新

    showPics = async() => {
        const {coords:{path}} = this.state;
        let {value} = await Storage.get({key: 'path' })
        let arrayPath = JSON.parse(value);
        const paths = [...path];
    
        for( let i=0; i < arrayPath.length; i++) {
            let newArray = {lat: arrayPath[i].latitude, lng: 
            arrayPath[i].longitude}
            paths.push(newArray)
        }
        this.setState({
           coords: {
             path: [...paths]
           }
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2020-06-16
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2021-09-18
      相关资源
      最近更新 更多