简体   繁体   English

React Native useEffect 重新渲染初始状态

[英]React Native useEffect rerenders with initial states

In the code below, when the app loads initially "Location changed offline."在下面的代码中,当应用程序最初加载时“位置已离线更改”。 is logged every time the location updates.每次位置更新时都会记录。 When online is set to true with a TouchableOpacity, the message logged to the console looks like this:当使用 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!

For some reason it's randomly changing the state of online back to false, thus causing the "Location changed offline."由于某种原因,它随机将online的 state 更改为 false,从而导致“位置已离线更改”。 to be logged?被记录? What could be causing this?这可能是什么原因造成的?

  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]);

The problem here is that you add a new watcher every time online changes that captures the current value forever.这里的问题是,每次online更改时,您都会添加一个新的观察者来永久捕获当前值。

Adding subscriptions (like Geolocation.watchPosition() ) within an effect hook should always be removed in the cleanup function.在效果挂钩中添加订阅(如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]);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM