React中每10秒检测API返回地理坐标数组是否增长的实现
在React定时请求中判断坐标数组是否增长的解决方案
我来帮你搞定这个问题!核心思路就是保存上一次请求得到的坐标数组长度,每次新请求返回数据后,和之前的长度做对比,就能轻松判断数组是否处于增长状态了。下面是具体的实现步骤和修改后的完整代码:
实现步骤
- 首先给组件的
state新增两个状态:prevCoordinateCount:用来存储上一次请求返回的坐标数组长度,初始值设为0isGrowing:用来标记数组是否增长的布尔值,初始值设为false
- 在
fetchData方法中,拿到新的API数据后,计算新数组的长度,和prevCoordinateCount对比得出是否增长 - 更新
state时,同步把prevCoordinateCount更新为当前新数组的长度,同时设置isGrowing的结果 - 你可以根据业务需求使用
isGrowing状态,比如打印日志、在页面上展示判断结果等
修改后的完整代码
import React from 'react'; import { GoogleMap, withScriptjs, withGoogleMap, Marker, Polyline} from 'react-google-maps'; import '../App.css'; import { Link } from "react-router-dom"; import Test4 from "./Test4"; class Map extends React.Component { // 扩展state,新增存储上一次长度和是否增长的状态 state = { loading: true, coordinates: null, time: null, prevCoordinateCount: 0, // 存储上一次的坐标数组长度 isGrowing: false // 标记数组是否增长 } fetchData = async() => { const url = "https://ttr.vsbbn.nl:4000/gps_history?team_id=7"; const response = await fetch(url); const data = await response.json(); // 判断当前数组是否比上一次长 const newCount = data.length; const isGrowing = newCount > this.state.prevCoordinateCount; // 更新state,同步保存新长度和判断结果 this.setState({ coordinates: data, loading: false, prevCoordinateCount: newCount, // 更新为当前新数组的长度 isGrowing: isGrowing }); // 可以在这里打印结果,或者触发其他业务逻辑 console.log('本次请求后数组是否增长:', isGrowing); } async componentDidMount(){ await this.fetchData(); setInterval( () =>{ this.fetchData(); console.log('fetching'); }, 1000 * 10 ) } render = () => { const { loading, coordinates, time, isGrowing} = this.state; if(loading == false){ let fetchCoordinates = coordinates.map(coordinate => { const single_coord = {lat: parseFloat(coordinate.lat), lng: parseFloat(coordinate.lon)} return single_coord; }) return( <> {/* 示例:在页面上展示判断结果 */} <div style={{marginBottom: '10px'}}>坐标数组是否增长: {isGrowing ? '是' : '否'}</div> <GoogleMap defaultZoom={14} defaultCenter={{ lat: fetchCoordinates[0].lat , lng: fetchCoordinates[0].lng }} > <Polyline path={fetchCoordinates} options={{ strokeColor: "#FF0000 " }} /> <Marker position={fetchCoordinates[fetchCoordinates.length - 1]} /> </GoogleMap> </> ) }else{ return(<div>Neem contact op met de developers. Server staat namelijk uit!</div>) } } } const WrappedMap = withScriptjs(withGoogleMap(Map)); export default() => ( <div> <br/> <b>Klik <Link to="/home" className="btn btn-primary">hier</Link> om terug te gaan naar teamoverzicht</b> <br/> <br/> <h3>Live kaart</h3> <p> Teamnaam: Hogeschool Rotterdam 3 (LIVE)<br/> Live:<span class="dot2"></span><br/> Actuele snelheid: 0 km per uur <br/> Gemiddelde snelheid: 0.05 km per uur <br/> Verwachte aankomsttijd Rotterdam: Onbekend <br/> <div></div> </p> <div style={{width: '50vw', height: '50vh'}}> <WrappedMap googleMapURL = {'https://maps.googleapis.com/maps/api/js?key=AIzaSyB9w0T_VMezCy1AaqxXpRie9ChrbVCt1O4&v=3.exp&libraries=geometry,drawing,places'} loadingElement={<div style={{ height: `100%` }} />} containerElement={<div style={{ height: `100%` }} />} mapElement={<div style={{ height: `100%` }} />} /> </div> </div> )
额外说明
- 第一次请求时,因为
prevCoordinateCount初始值是0,只要API返回的数组长度大于0,isGrowing就会设为true,这符合“从无到有属于增长”的预期 - 如果API返回的数组可能出现长度不变或者减少的情况,这个逻辑也能正确处理
- 你可以把
isGrowing状态用在任何需要的地方,比如触发提示、更新其他组件状态等
内容的提问来源于stack exchange,提问作者K.V.
相关产品推荐
相关产品推荐

