You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Expo项目render内调用经纬度变量报未定义错误

问题根源

  • 你在recalcularGPS函数内声明的b、c属于函数局部变量,没有存入组件state,因此render方法中从state解构b、c只能拿到undefined
  • 你给getPreciseDistance传参的格式错误:{latitude: {b}}是给latitude赋值了一个{b: 数值}的对象,不是方法要求的数值类型
  • item.Point是字符串格式,getPreciseDistance要求传入坐标对象,需要先做格式转换

修正代码

首先修改render方法内的距离计算逻辑,直接复用你已经从state解构出的coords变量即可,不需要额外声明b、c:

render() {
  const { position, fill, coords, coordsBest, Data } = this.state;
  console.log('coordsBest', coordsBest);
  console.log(coords.latitude, coordsBest.latitude);

  let DistancesFromUserLocation = [];
  // 坐标获取完成后再计算距离,避免NaN
  if (coords.latitude && coords.longitude) {
    Data.forEach((item) => {
      // 将Point字符串拆分转换为数值类型的经纬度
      const [pointLat, pointLon] = item.Point.split(',').map(coord => Number(coord.trim()));
      DistancesFromUserLocation.push(
        getPreciseDistance(
          // 直接使用已有的coords对象内的经纬度
          { latitude: coords.latitude, longitude: coords.longitude },
          { latitude: pointLat, longitude: pointLon }
        )
      );
    });
  }
  
  DistancesFromUserLocation = DistancesFromUserLocation.sort();
  const distances = DistancesFromUserLocation.map((distance, index) => (
    <Text key={index}>{distance},</Text>
  ));
  
  return (
    <View style={styles.container}>
      {coords && (
        <View style={{ paddingVertical: 10 }}>
          <Text>dist0: {distances[0]}</Text>
          <Text>distances: {distances}</Text>
          <Text>Lat: {coords.latitude}</Text>
          <Text>Lon: {coords.longitude}</Text>
        </View>
      )}      
    </View>
  );
}

另外你recalcularGPS方法里的错误回调逻辑位置错误,也可以同步修正,避免潜在报错:

recalcularGPS = async () => {
  clearInterval(this.idInterval);
  try {
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: true,
      accuracy: Location.Accuracy.higher,
      timeout: 5000,
    });
    const { latitude, longitude, speed, accuracy } = location.coords;
    const { coordsBest } = this.state;

    // 合并两次setState操作,减少不必要的重渲染
    await this.setState((previousState) => ({
      latitude,
      longitude,
      speed,
      error: null,
      position: accuracy.toFixed(2),
      fill: accuracy.toFixed(1),
      coords: location.coords,
      coordsBest: !coordsBest.accuracy || coordsBest.accuracy > accuracy ? location.coords : coordsBest,
      regionInicial: {
        ...previousState.regionInicial,
        latitude,
        longitude,
        speed,
      },
    }));
  } catch (error) {
    this.setState({ error: error.message });
  }
  this.startTimeInterval();
};

内容的提问来源于stack exchange,提问作者Caquibf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:57:03