问题描述
作为 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")}
({moment.unix(gpsPoint['time']/1000.).fromNow()})
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 (将#修改为@)