javascript - React-Leaflet 多边形不会被重新渲染

标签 javascript reactjs react-leaflet

我正在尝试使用 react 状态来制作动态多边形,但传单多边形不会被重新渲染。

目标是创建用户在 map 中单击创建的多边形。

class SimpleExample extends React.Component {
constructor() {
  super();
  this.state = {
    positions: [[51.505, -0.09]]
  };
}

addPosition = (e) => {
  const {positions} = this.state
  console.log('Adding positions', positions)
  positions.push([e.latlng.lat, e.latlng.lng])
  this.setState({positions})
}

render() {
    console.log('Should render new positions', this.state.positions)
    const staticPositions = [[51.505, -0.09], [51.4958128370432, -0.10728836059570314], [51.49602657961649, -0.09956359863281251]]
  return (
    <Map 
      center={[51.505, -0.09]} 
      onClick={this.addPosition}
      zoom={13} 
      >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
      />
      <Polygon positions={this.state.positions} color="blue" />
      <Polygon positions={staticPositions} color="red" />
      <Polyline positions={this.state.positions} />
    </Map>
  );
}
}

请检查这个 fiddle : https://jsfiddle.net/cesargdm/j2g4ktsg/1/

最佳答案

您可以将其复制到 jsfiddle 中,它应该可以工作。希望对您有所帮助。

我的初始状态为空数组,因此您的第一次单击决定您开始绘制 <Polygon> 的位置。 ,当然你可以使用初始坐标,这完全取决于你。

使用箭头函数(prevState) => {}您可以根据您的“先前状态”正确更新状态,这里我们采用新坐标并使用 concat()将其添加到我们的 positions状态。

您可以找到有关更新状态的更多信息 here .

const React = window.React;
const { Map, TileLayer, Marker, Popup, Polygon } = window.ReactLeaflet;

class SimpleExample extends React.Component {
  constructor() {
    super();
    this.state = {
      positions: []
    };
  }

  addPosition = (e) => {
    const newPos = [e.latlng.lat, e.latlng.lng];
    this.setState(prevState => (
      {
        positions: prevState.positions.concat([newPos])
      }
    ));
  }

  render() {

    return (
      <Map 
        center={[51.505, -0.09]} 
        onClick={this.addPosition}
        zoom={13}>
        <TileLayer attribution='&copy; <ahref="http://osm.org/copyright">
          OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <Polygon positions={this.state.positions} color="blue" />
      </Map>
    );
  }
 }
 window.ReactDOM.render(<SimpleExample />, 
  document.getElementById('container'));

关于javascript - React-Leaflet 多边形不会被重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889170/

相关文章:

javascript - 将模式表单中的数据注入(inject) AngularJS 中的父表单?

javascript - 使用以秒为单位的偏移量将 utc 时间戳转换为本地时间

javascript - Angular 2+ 中的 Google 登录按钮

twitter-bootstrap - React 传单未正确渲染

javascript - onload 和 onLocationfound 等事件处理函数不起作用,函数未执行

javascript - 选择 INTO 数组或对象

Reactjs结合unity webgl导致错误

javascript - 如何在 admin-on-rest 上实现嵌套表单?

javascript - 如何在 ReactJS 应用程序的服务器端导入模块 'child_process'

javascript - 如何在传单控件搜索结果上显示 2 个值(工具提示)