微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

由于管理不善的 React 状态,“google-map-react”折线无法绘制

如何解决由于管理不善的 React 状态,“google-map-react”折线无法绘制

作为 React TS 的新手,我需要一些有关管理 sessionEntity 变量的帮助。

我使用名为 getEntity()函数数据库加载数据。在开发环境中。下面的代码工作得很好。在我预计加载数据需要更长的时间的生产环境中,从不绘制折线。我假设这是因为在加载 handleApiLoaded() 之前调用了我的函数 sessionEntity

我确定在加载 sessionEntity 的某个地方存在一个愚蠢的错误。基本上,我希望在加载 handleApiLoaded() 和安装 sessionEntity 之后调用 map

请帮忙。

import React,{useEffect,useState} from 'react';
import { getEntity } from 'app/entities/session/session.reducer';
import { connect } from 'react-redux';
import './dashboard.css';
import * as moment from 'moment'
import * as chart from 'react-chartjs-2';

const location = {
  address: 'My location',lat: 21.161791151500324,lng: 52.75883610045212
}


import GoogleMapReact from 'google-map-react';
import Marker from './Marker';
import {RouteComponentProps} from "react-router";
import {IRootState} from "app/shared/reducers";
import {getUrlParameter} from "react-jhipster";


export interface ISessionDetailProps extends StateProps,dispatchProps,RouteComponentProps<{ id: string }> {}

export const Dashboard = (props: ISessionDetailProps) => {
  useEffect(() => {
    const sessionID = getUrlParameter('sessionID',props.location.search);
    props.getEntity(sessionID); // id
    // this.state.loaded = true;
  },[]);

  const [center,setCenter] = useState({lat: location.lat,lng: location.lng });
  const [zoom,setZoom] = useState(14);
  const listofMarkers = [],listofHistory = [];
  const { sessionEntity } = props;
  // const [ sessionEntity,setSessionEntity ] = useState(props.sessionEntity);

  const convertReadingData = (data: any)=> {
    const labels1 = [];
    const readings = [];


    if (!data) return {};

    data.forEach(rate  => {
           labels1.push(rate.time);
           readings.push(rate.reading);
         });

    // console.log(labels,readings);
    // return {};
    return  {
      labels: labels1,// [0,1,2,3,4,5],datasets: [
        {
          label: 'My First dataset',fill: false,lineTension: 0.1,backgroundColor: 'rgba(75,192,0.4)',borderColor: 'rgba(75,1)',borderCapStyle: 'butt',borderDash: [],borderDashOffset: 0.0,borderJoinStyle: 'miter',pointBorderColor: 'rgba(75,pointBackgroundColor: '#fff',pointBorderWidth: 1,pointHoverRadius: 5,pointHoverBackgroundColor: 'rgba(75,pointHoverBorderColor: 'rgba(220,220,pointHoverBorderWidth: 2,poinTradius: 1,pointHiTradius: 10,data: readings,// [72,71,70,73,75]
        }
      ]
    };
  }
  // eslint-disable-next-line no-console
  // console.log(sessionEntity);


  const getMapOptions = (maps: any) => {
    return {
      disableDefaultUI: false,mapTypeControl: true,streetViewControl: true,styles: [{ featureType: 'poi',elementType: 'labels',stylers: [{ visibility: 'on' }] }],};
  };

  // Re-center map when resizing the window
  const bindResizeListener = (map,maps,bounds) => {
    maps.event.addDomListenerOnce(map,'idle',() => {
      maps.event.addDomListener(window,'resize',() => {
        map.fitBounds(bounds);
      });
    });
  };

  const handleApiLoaded = (map,mySessionEntity) => {


    if(mySessionEntity!=null && mySessionEntity.gpsData!=null){
      // create polyLines
      for(let i=0; i<mySessionEntity.gpsData.length-1;i++){
        const gpsPoint =mySessionEntity.gpsData[i];
        const nextGpsPoint =mySessionEntity.gpsData[i+1];

        const polyline1 = new maps.polyline({
          path: [{'lat':gpsPoint['latitude'],'lng':gpsPoint['longitude']},{'lat':nextGpsPoint['latitude'],'lng':nextGpsPoint['longitude']}],geodesic: true,strokeColor: '#33BD4E',strokeOpacity: 1,strokeWeight: 5
        });
        polyline1.setMap(map);
      }

      const bounds = new maps.LatLngBounds();
      for(const gpsPoint of mySessionEntity.gpsData){
        const latLng = {'lat':gpsPoint['latitude'],'lng':gpsPoint['longitude']};
        bounds.extend(latLng);
      }
      // console.log(bounds);
      map.fitBounds(bounds);
      bindResizeListener(map,bounds);

    }
  };


  if(sessionEntity!=null && sessionEntity.gpsData!=null){
    // create Markers
    let id = 0;
    for(const gpsPoint of sessionEntity.gpsData) {
      listofMarkers.push(
        <Marker
          id={id}
          lat={gpsPoint['latitude']}
          lng={gpsPoint['longitude']}
          name="My Marker"
          color="blue"
        />
       );
      id = id+1;
    }
  }

  if(sessionEntity!=null && sessionEntity.gpsData!=null){
    // create history
    let id = 0;
    for(const gpsPoint of sessionEntity.gpsData) {
      listofHistory.push(<div> #{id}  on  {moment.unix(gpsPoint['time']/1000.).format("MM/DD/YYYY HH:mm:ss")}
                        &nbsp; ({moment.unix(gpsPoint['time']/1000.).fromNow()})
                        &nbsp; 0 ft traveled at {gpsPoint['speed']} kph <br /></div>);
      id = id+1;
    }
  }

  return (

    <div className="container-fluid">
      <div className="user">
        <img src={'./../../../content/images/jhipster_family_member_0_head-192.png'}/>
        <h3>My Name</h3>
        <span></span>
      </div>
      <div className="row">
        <div className="col-md-8">
          <div style={{ height: '80vh',width: '100%' }}>
            <GoogleMapReact
              bootstrapURLKeys={{ key: 'AIzaSyDcrYZgCwaK0R7IzFrytA1dPc3E4BnlQAc' }}
              defaultCenter={center}
              defaultZoom={zoom}
              options={getMapOptions}
              yesIWantToUseGoogleMapApiInternals
              onGoogleApiLoaded={({ map,maps }) => handleApiLoaded(map,sessionEntity)}
            >
              {listofMarkers}
            </GoogleMapReact>
          </div>

        </div>
        <div className="col-md-4">
          <div className="card">
            <div className="card-header">
              <h6>Stats</h6>
            </div>
            <div className="card-body">
              <table className="table table-striped text-center user-stats">
                <tr>
                  <td>Last Updated</td>

                  <td>{moment.utc(sessionEntity.lastUpdated).format('Y-MM-DD HH:mm:ss')}</td>
                </tr>
                <tr>
                  <td>Started Time</td>
                  <td>{moment.utc(sessionEntity.startedDateTime).format('Y-MM-DD HH:mm:ss')}</td>
                </tr>
                <tr>
                  <td>Current Speed</td>
                  <td>{sessionEntity.currentSpeed}</td>
                </tr>
                <tr>
                  <td>Moving Time (sec)</td>
                  <td>{sessionEntity.movingTimeInSeconds}</td>
                </tr>
                <tr>
                  <td>Stopped Time (sec)</td>
                  <td>{sessionEntity.stoppedTimeInSeconds}</td>
                </tr>
                <tr>
                  <td>Finished?</td>
                  <td>{sessionEntity.finished == null ? 'False' : sessionEntity.finished ? 'True' : 'False'}</td>
                </tr>
                <tr>
                  <td>Finished Time</td>
                  <td>{moment.utc(sessionEntity.finishedDateTime).format('Y-MM-DD HH:mm:ss')}</td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </div>
      <div className="row mt-5">
        <div className="col-md-8">
          <h3>Recent History</h3>
          <div>{listofHistory}</div>
        </div>
      </div>
      <div className="row mt-5">
        <div className="col-md-8">
          <h3>Heart Rate Chart</h3>
          <chart.Line
            data={convertReadingData(sessionEntity?.heartRate)}
            height
              ={25}
            width={100}
          />
        </div>
      </div>
      <div className="row mt-5">
        <div className="col-md-8">
          <h3>Temperature Sensor Chart</h3>
          <chart.Line
            data={convertReadingData(sessionEntity?.temperatureData)}
            height={25}
            width={100}
          />
        </div>
      </div>
    </div>
  );
}



const mapStatetoProps = ({ session }: IRootState) => ({
  sessionEntity: session.entity,});

const mapdispatchToProps = { getEntity };

type StateProps = ReturnType<typeof mapStatetoProps>;
type dispatchProps = typeof mapdispatchToProps;

export default connect(mapStatetoProps,mapdispatchToProps)(Dashboard);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?