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

时间:2020-09-14 23:54:22

标签: javascript reactjs redux react-redux react-leaflet

我无法使用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);

0 个答案:

没有答案