第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

React useEffect 避免每次更新中的更新回調(diào)

React useEffect 避免每次更新中的更新回調(diào)

富國(guó)滬深 2022-10-21 10:32:01
有沒有辦法避免更新 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},          });        },      );    })();  
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊

您是否檢查過返回條件是否適用于頁(yè)面加載(只需在其中放置控制臺(tái)日志)?

從閱讀來(lái)看,似乎兩個(gè) useEffects 都在頁(yè)面加載時(shí)被調(diào)用,但第二個(gè)應(yīng)該立即退出,然后在第一個(gè)完成后再次被調(diào)用。

然后我注意到您通過異步回調(diào)更新狀態(tài),這可能與它有關(guān)。很難說沒有看到它在行動(dòng)。

我會(huì)說嘗試用函數(shù)而不是對(duì)象重寫你的 setCurrentLocation:

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

也許它沒有通過并在新舊數(shù)據(jù)之間切換。


查看完整回答
反對(duì) 回復(fù) 2022-10-21
  • 1 回答
  • 0 關(guān)注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)