如何在我的React-Leaflet组件中设置setState

问题描述

我无法使用setState更新我的componentDidMount中的状态。我有一个axios调用,该调用处理对我的api的异步调用,并加载一个匿名函数,该匿名函数应在用户单击geoJSON层时更新状态。由于某些原因,点击时不会更新redux存储,并且该存储仍为空字符串的初始状态。我的代码在下面

import React from 'react';
import L from 'leaflet';
import {apiKey} from './apiKey';
import { connect } from 'react-redux';
import axios from 'axios';
import {districtStyle,districtHighlightStyle,mapStyle} from './styles';

class Map extends React.Component {

  componentDidMount() {

    let districtsJSON = null;

    this.map = L.map('map').setView([31.15,-99.90],6);

    L.tileLayer(`https://{s}.tile.thunderforest.com/pioneer/{z}/{x}/{y}.png?apikey=${apiKey}`,{
      attribution: 'Pioneer Basemap by Thunderforest,a project by Gravitystorm Limited.'
    }).addTo(this.map);


    const districtsUrl = 'http://localhost:8000/gerrymander/api/districts/';
    axios.get(districtsUrl).then(
      response => {
        districtsJSON = response.data;

        const txDistricts = L.geoJson(districtsJSON,{
          style: districtStyle,onEachFeature: (feature,layer) => {
            layer.on({
              click: (e) => {
                if (lastClickedLayer !== e.target) {
                  txDistricts.setStyle(districtStyle);
                }
                e.target.setStyle(districtHighlightStyle);
                let lastClickedLayer = e.target;
                // Set state to the target layer's clicked district
                this.setState({ district: e.target.feature.properties.namelsad })
              }
            });
          }
        }).addTo(this.map);
      }
    )
    console.log(this.props.district);
  }

  render() {
    return <div id="map" style={mapStyle}></div>
  }
}


const mapStateToProps = state => {
  return {
    district: state.district,}
}

export default connect(mapStateToProps)(Map);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...