簡體   English   中英

React Native useEffect 重新渲染初始狀態

[英]React Native useEffect rerenders with initial states

在下面的代碼中,當應用程序最初加載時“位置已離線更改”。 每次位置更新時都會記錄。 當使用 TouchableOpacity 將online設置為 true 時,記錄到控制台的消息如下所示:

 LOG  true
 LOG  attempting to update location...
 LOG  Location updated in real-time!
 LOG  false
 LOG  Location changed offline!
 LOG  true
 LOG  attempting to update location...
 LOG  true
 LOG  attempting to update location...
 LOG  Location updated in real-time!

由於某種原因,它隨機將online的 state 更改為 false,從而導致“位置已離線更改”。 被記錄? 這可能是什么原因造成的?

  const [online, setOnline] = useState(false);

  useEffect(() => {
    Geolocation.watchPosition(
      position => {
        console.log(online);
        if (online) {
          console.log('attempting to update location...');
          const payload = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            id: 1,
          };

          axios
            .post('http://localhost:3000/location/update', payload)
            .then(res => {
              if (res.status === 200) {
                console.log('Location updated in real-time!');
                return;
              }
            })
            .catch(err => console.log(err.response));
        } else {
          console.log('Location changed offline!');
        }
      },
      err => console.log(err.response)
    );
  }, [online]);

這里的問題是,每次online更改時,您都會添加一個新的觀察者來永久捕獲當前值。

在效果掛鈎中添加訂閱(如Geolocation.watchPosition() )應始終在清理 function 中刪除。

useEffect(() => {
  const watchId = Geolocation.watchPosition(async (position) => {
    console.log("online?", online);
    if (online) {
      console.log("attempting to update location...");
      const payload = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
        id: 1,
      };

      try {
        await axios.post("http://localhost:3000/location/update", payload);

        // no need to check the response status
        console.log("Location updated in real-time!");
      } catch (err) {
        console.warn(err.toJSON()); // Axios helper, much nicer to look at
      }
    } else {
      console.log("Location changed offline!");
    }
  }, console.error);

  // return a cleanup function
  return () => {
    Geolocation.clearWatch(watchId);
  };
}, [online]);

https://reactnative.dev/docs/0.63/geolocation#clearwatch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM