有沒有辦法避免更新 useEffect 中的回調(diào)?例如,我使用geofire訂閱了一個(gè)事件,它會(huì)監(jiān)聽更改并接收位置。我需要更新我的狀態(tài),而無(wú)需每次更新時(shí)都訂閱。當(dāng)前行為訂閱 geofire 并接收位置 (A)用新位置更新我的狀態(tài) (A)再次訂閱geofire并接收位置(A)這是一個(gè)無(wú)限循環(huán)。而且我無(wú)法接收其他位置預(yù)期行為僅訂閱一次 geofire 并接收位置 (A,B,C)使用新位置(A、B、C)更新我的狀態(tài)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}, }); }, ); })();
React useEffect 避免每次更新中的更新回調(diào)
富國(guó)滬深
2022-10-21 10:32:01