1

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

我使用一个名为getEntity(). 在开发环境中。下面的代码工作得很好。在我预计加载数据需要更长时间的产品环境中,折线永远不会被绘制。我假设那是因为我的函数在加载handleApiLoaded()之前被调用。sessionEntity

我敢肯定我加载的方式有一个愚蠢的错误sessionEntity。基本上,我想在加载和安装handleApiLoaded()后被调用。sessionEntitymap

请帮忙。

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,192,0.4)',
          borderColor: 'rgba(75,192,192,1)',
          borderCapStyle: 'butt',
          borderDash: [],
          borderDashOffset: 0.0,
          borderJoinStyle: 'miter',
          pointBorderColor: 'rgba(75,192,192,1)',
          pointBackgroundColor: '#fff',
          pointBorderWidth: 1,
          pointHoverRadius: 5,
          pointHoverBackgroundColor: 'rgba(75,192,192,1)',
          pointHoverBorderColor: 'rgba(220,220,220,1)',
          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, maps, 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, maps, 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, maps, 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);
4

0 回答 0