我有一个简单的组件来在 map 上选取点,然后显示与该点相关的一些 GeoJSON 数据:

import React, { Component } from 'react'; 
 
import { Map, Marker, TileLayer, GeoJSON } from 'react-leaflet'; 
import 'leaflet/dist/leaflet.css'; 
 
import { connect } from 'react-redux'; 
import './style.css'; 
 
import { setPoint, fetchData } from '../../actions/map'; 
 
@connect(store => { 
  return { 
    map: store.map 
  } 
}) 
class MyMap extends Component { 
 
  mapClick(e) { 
    this.props.dispatch(setPoint(e.latlng)); 
    this.props.dispatch(fetchData(e.latlng)); 
  } 
 
  render() { 
    const marker = () => { 
      if(this.props.map.point) { 
        return <Marker position={this.props.map.point} />; 
      } 
    }; 
 
    const data = () => { 
        if(this.props.map.data.length > 0) { 
            const json = this.props.map.data; 
            return <GeoJSON data={json} /> 
        } 
    } 
 
    return ( 
      <div className='my-map'> 
        <div className='my-map__map-container'> 
          <Map center={this.props.map.center} zoom={13} onClick={this.mapClick.bind(this)}> 
            <TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> 
            {marker()} 
            {data()} 
          </Map> 
        </div> 
        <div className='my-map__debug'> 
            {JSON.stringify(this.props.map)} 
        </div> 
      </div> 
    ); 
  } 
} 
 
export default MyMap; 

第一次,我点击 map 标记出现,经过一段时间的延迟(XHR 请求)后,GeoJSON 呈现。但下次我单击 map 时,仅标记位置发生变化,但旧的 GeoJSON 数据仍保留在 map 上。调试组件的一部分正确呈现,并显示正确的数据。如何强制 react-leaflet 重新渲染我的 GeoJSON 数据,或者我可能做错了什么?

更新:

在询问了 react-leafet 的作者后,我找到了如何达到预期的行为。

为了强制使用react以重新渲染我的 GeoJSON 数据,我需要将一些 data-uniq key 传递给组件:

<GeoJSON key={keyFunction(this.props.map.data.json)} data={this.props.map.data.json} /> 

https://github.com/PaulLeCam/react-leaflet/issues/332#issuecomment-304228071

请您参考如下方法:

在询问了 react-leafet 的作者后,我找到了如何达到预期的行为。

为了强制使用react以重新渲染我的 GeoJSON 数据,我需要将一些 data-uniq key 传递给组件:

<GeoJSON key={keyFunction(this.props.map.data.json)} data={this.props.map.data.json} /> 

https://github.com/PaulLeCam/react-leaflet/issues/332#issuecomment-304228071


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!