【问题标题】:React question about geofire and useEffect反应关于 geofire 和 useEffect 的问题
【发布时间】:2020-06-07 23:10:12
【问题描述】:

我有一个关于反应的问题,虽然我没有太多经验。我正在尝试使用geoFire 进行查询,然后在我的数据库中找到数据后获取位置。

Geofire 创建一个我订阅的事件并向我发送最近的位置。

此时我有一个查询 geoFire 和一个 useEffect 我确实在我的状态下更新 data 以缓存这些值。

当我更新我的状态时,此操作会中断 geofire 事件,并且必须从头开始。所以这是个问题?还是有更好的解决方案?

方法getQuery

const firebaseRef: any = database().ref();
const geoFire = new GeoFire(firebaseRef);

  static getQuery(currentLocation: [number, number], radius: number): GeoQuery {
  return geoFire.query({
    center: currentLocation,
    radius,
  });
}
import React, {useState, useEffect} from 'react';
import {View, Text} from 'react-native';
import {GeoPosition, GeoError} from 'react-native-geolocation-service';
import {GeoQuery} from 'geofire';

import {getCurrentLocation, LocationInfo} from '../../util/geolocation';

import GeoFireService, {EVENT_TYPE} from './services/GeoFireService';
// import AdService from './services/AdService';

interface CurrentLocation {
  [key: string]: {
    location: [number, number];
    distance: number;
  };
}

const Ads = () => {
  const [locationInfo, setLocationInfo] = useState({
    latitude: 0,
    longitude: 0,
    altitude: 0,
    accuracy: 0,
  } as LocationInfo);
  const [query, setQuery]: [GeoQuery | null, Function] = useState(null);
  const [currentLocation, setCurrentLocation] = useState({} as CurrentLocation);

  // set the current location
  useEffect(() => {
    getCurrentLocation(
      (position: GeoPosition) => {
        const {latitude, longitude, accuracy, altitude} = position.coords;
        setLocationInfo({latitude, longitude, accuracy, altitude});
      },
      (err: GeoError) => {
        console.log(err);
      },
    );
  }, []);

  // set the event query
  useEffect(() => {
    (async () => {
      const geoFireQuery = await GeoFireService.getQuery(
        [-34.5742746, -58.4744191],
        30,
      );
      setQuery(geoFireQuery);

      return () => geoFireQuery.cancel();
    })();
  }, []);

  useEffect(() => {
    if (query) {
      (query as GeoQuery).on(
        EVENT_TYPE.KEY_ENTERED,
        (key: string, location: [number, number], distance: number) => {
          console.log(key);
          if (!currentLocation[key]) {
            setCurrentLocation({
              ...currentLocation,
              [key]: {location, distance},
            });
          }
        },
      );
    }
  }, [query, currentLocation]);

  return (
    <View>
      <Text>
        Latitude: {locationInfo.latitude} Longitude: {locationInfo.longitude}
      </Text>

      {Object.keys(currentLocation).map((key: string) => (
        <Text key={key}>
          Ubicacion: {key}, Km: {currentLocation[key].distance.toFixed(2)}
        </Text>
      ))}
    </View>
  );
};

export default Ads;

此刻我有 3 个位置,但这重复太多了。控制台输出应该只显示三个位置

[Sun Jun 07 2020 20:06:14.990]  LOG      1wr0cDenn4DmJ8S0xraG
[Sun Jun 07 2020 20:06:14.120]  LOG      58zvRXriUELSW96HprHh
[Sun Jun 07 2020 20:06:14.121]  LOG      58zvRXriUELSW96HprHh
[Sun Jun 07 2020 20:06:14.122]  LOG      58zvRXriUELSW96HprHh
[Sun Jun 07 2020 20:06:14.134]  LOG      58zvRXriUELSW96HprHh
[Sun Jun 07 2020 20:06:14.145]  LOG      1wr0cDenn4DmJ8S0xraG
[Sun Jun 07 2020 20:06:14.158]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.159]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.160]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.174]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.187]  LOG      1wr0cDenn4DmJ8S0xraG
[Sun Jun 07 2020 20:06:14.188]  LOG      58zvRXriUELSW96HprHh
[Sun Jun 07 2020 20:06:14.189]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.198]  LOG      1wr0cDenn4DmJ8S0xraG
[Sun Jun 07 2020 20:06:14.199]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.240]  LOG      2Y5DBEsPQ1eFosxoAimB
[Sun Jun 07 2020 20:06:14.286]  LOG      1wr0cDenn4DmJ8S0xraG

【问题讨论】:

  • 看起来你的 useEffect 有if (query) 被配置为在每个渲染上运行(因为没有依赖数组),而且看起来这会重新订阅query.on 这给你一个新的键,你添加到 state 中,它会触发重新渲染,再次运行 if (query) useEffect ...等等。你希望最后一个 useEffect 只在 mount 上运行一次吗?
  • 嗨@DonaldP,是的,我只想运行最后一个useEffect,但是已经将它用作componentDidMout,它对我不起作用。因为只运行一次并且没问题,但是 React 不会使用新值更新状态。我用[]和[query, setCurrentLocation]最后一个选项是一样的输出
  • 当您说“React 不更新状态”时,您的意思是 setCurrentLocation 调用没有按照您的预期进行吗?看起来它应该更新存储在包含它们的键的状态中的数组。
  • 你检查我的答案了吗?
  • @DonaldP 是的,这个[query, currentLocation] 的问题在于它再次调用了on 事件。输出是一样的。

标签: reactjs typescript firebase react-native geofire


【解决方案1】:

你是最后一个 useEffect 调用在每个渲染上运行,它需要一个依赖项 query。如果您像下面这样更改代码,您就可以开始了:

useEffect(() => {
    if (query) {
      (query as GeoQuery).on(
        'key_entered',
        (key: string, location: [number, number], distance: number) => {
          if (!currentLocation.includes(key)) {
            console.log(key);
            setCurrentLocation([...currentLocation, key]);
          }
        },
      );
    }
  }, [query]); // <-- Add query as dependency

【讨论】:

  • 我试过了。但它不会更新我的状态currentLocation。输出正确,仅显示 3 个位置
猜你喜欢
  • 2020-12-20
  • 2021-01-16
  • 2021-11-23
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2021-07-31
  • 1970-01-01
相关资源
最近更新 更多