繁体   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