首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用初始状态响应本机useEffect重发器

用初始状态响应本机useEffect重发器
EN

Stack Overflow用户
提问于 2022-09-01 01:23:07
回答 1查看 57关注 0票数 2

在下面的代码中,当应用程序最初加载“位置变化离线!”每次位置更新时都会记录。当online设置为TouchableOpacity时,记录到控制台的消息如下所示:

代码语言:javascript
复制
 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状态更改为false,从而导致“位置离线更改!”被记录下来。是什么导致了这一切?

代码语言:javascript
复制
  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]);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-01 01:32:01

这里的问题是,每次online更改时都会添加一个新的观察者来永远捕获当前值。

在效果钩子中添加订阅(如Geolocation.watchPosition())应始终在清除函数中删除。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73563408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档