为了账号安全,请及时绑定邮箱和手机立即绑定

React useEffect 避免每次更新中的更新回调

React useEffect 避免每次更新中的更新回调

富国沪深 2022-10-21 10:32:01
有没有办法避免更新 useEffect 中的回调?例如,我使用geofire订阅了一个事件,它会监听更改并接收位置。我需要更新我的状态,而无需每次更新时都订阅。当前行为订阅 geofire 并接收位置 (A)用新位置更新我的状态 (A)再次订阅geofire并接收位置(A)这是一个无限循环。而且我无法接收其他位置预期行为仅订阅一次 geofire 并接收位置 (A,B,C)使用新位置(A、B、C)更新我的状态import React, {useState, useEffect} from 'react';import {View, Text} from 'react-native';import {GeoPosition, GeoError} from 'react-native-geolocation-service';import {getCurrentLocation, LocationInfo} from '../../util/geolocation';import GeoFireService, {EVENT_TYPE} from './services/GeoFireService';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 [currentLocation, setCurrentLocation] = useState({});  // 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);      },    );  }, []);  // get ads  useEffect(() => {    (async () => {      if (locationInfo.latitude === 0 && locationInfo.longitude === 0) {        return null;      }      // this must be execute only once      await GeoFireService.queryToRadius(        [-34.5742746, -58.4744191],        30,        (key: string, location: [number, number], distance: number,) => {          // update state           setCurrentLocation({            ...currentLocation,            [key]: {location},          });        },      );    })();  
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

您是否检查过返回条件是否适用于页面加载(只需在其中放置控制台日志)?

从阅读来看,似乎两个 useEffects 都在页面加载时被调用,但第二个应该立即退出,然后在第一个完成后再次被调用。

然后我注意到您通过异步回调更新状态,这可能与它有关。很难说没有看到它在行动。

我会说尝试用函数而不是对象重写你的 setCurrentLocation:

setCurrentLocation((currentLocation) => ({
    ...currentLocation,
    [key]: {location},}));

也许它没有通过并在新旧数据之间切换。


查看完整回答
反对 回复 2022-10-21
  • 1 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信