如何解决“React Hook useEffect 缺少依赖项:'currentPosition'”

如何解决如何解决“React Hook useEffect 缺少依赖项:'currentPosition'”

当我在 currentPosition 依赖数组中包含 useEffect 或删除它时,代码变成无限循环。为什么? 我对 map 有同样的问题,但是当我将 map 放在依赖数组中时就可以了。

import { useState,useEffect } from "react";

import { useMap } from "react-leaflet";
import L from "leaflet";

import icon from "./../constants/userIcon";

const UserMarker = () => {
  const map = useMap();
  const [currentPosition,setCurrentPosition] = useState([
    48.856614,2.3522219,]);

  useEffect(() => {
    if (navigator.geolocation) {
      let latlng = currentPosition;
      const marker = L.marker(latlng,{ icon })
        .addTo(map)
        .bindPopup("Vous êtes ici.");
      map.panTo(latlng);

      navigator.geolocation.getCurrentPosition(function (position) {
        const pos = [position.coords.latitude,position.coords.longitude];
        setCurrentPosition(pos);
        marker.setLatLng(pos);
        map.panTo(pos);
      });
    } else {
      alert("Problème lors de la géolocalisation.");
    }
  },[map]);

  return null;
};

export default UserMarker;

解决方法

来自 DCTID 的评论解释了在 useEffect 钩子中包含状态会导致无限循环的原因。

您需要确保不会发生这种情况!您有两个选择:

  1. 添加忽略评论并保持原样

  2. 创建一个额外的冗余变量来存储变量currentPosition的当前值,并且只有在值实际发生变化时才执行该函数

第二种方法的实现:

let currentPosition_store = [48.856614,2.3522219];

useEffect(() => {
    if (!hasCurrentPositionChanged()) {
        return;
    }

    currentPosition_store = currentPosition;

    // remaining function

    function hasCurrentPositionChanged() {
        if (currentPosition[0] === currentPosition_store[0] &&
            currentPosition[1] === currentPosition_store[1]
        ) {
            return false;
        }
        
        return true;
    }
},[map,currentPosition]);
,

为了便于理解,我先指出原因,然后再给出解决方案。

  1. 为什么?我对 map 有同样的问题,但是当我将 map 放在依赖数组中时就可以了。

Answer:原因是useEffect是基于它的依赖重新运行的。 useEffect 在组件渲染时第一次运行 -> 组件重新渲染(因为它的 props 改变了......) -> useEffect 将 shallow 比较并重新运行,如果它的依赖项发生变化。

  • 在你的情况下,map Leaflet Map 我敢打赌,如果你的组件只是重新渲染 -> 当你重新渲染组件时,react-leaflet 将返回相同的 Map 实例(相同的引用) -> {{ 1}}(Leaflet Map 实例)不要改变 -> useEffect 不会重新运行 -> 无限循环不会发生。
  • map 是你的本地状态,你在 useEffect 中更新它 currentPosition -> 组件重新渲染 -> setCurrentPosition(pos); 依赖项改变(currentPosition 在浅比较中不同) -> useEffect 重新运行 -> currentPosition 使组件重新渲染 -> 无限循环
  1. 解决方案:

有一些解决方案:

  • 通过在依赖项行正上方添加 setCurrentPosition(pos); 来禁用 lint 规则。但这根本不推荐。通过这样做,我们打破了 useEffect 的工作方式。
  • 拆分你的 useEffect:

// eslint-disable-next-line exhaustive-deps

Dan 有一篇关于 useEffect 的精彩文章,值得一看:https://overreacted.io/a-complete-guide-to-useeffect/#dont-lie-to-react-about-dependencies

,

谢谢,我已经解决了这个冲突:

import { useEffect } from "react";

import { useMap } from "react-leaflet";
import L from "leaflet";

import icon from "./../constants/userIcon";

const UserMarker = () => {
  const map = useMap();

  useEffect(() => {
    const marker = L.marker;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
        const latlng = [position.coords.latitude,position.coords.longitude];
        marker(latlng,{ icon })
          .setLatLng(latlng)
          .addTo(map)
          .bindPopup("Vous êtes ici.");
        map.panTo(latlng);
      });
    } else {
      alert("Problème lors de la géolocalisation.");
    }
  },[map]);

  return null;
};

export default UserMarker;
,

如果 currentPosition 在依赖数组中,你会得到无限循环的原因:

const [currentPosition,setCurrentPosition] = useState([
    48.856614,2.3522219,]);

您最初拥有 currentPosition 的值,然后您在 useEffect 内部进行更改,这会导致您的组件重新渲染,并且这种情况会无限发生。您不应将其添加到依赖项数组中。

您收到“缺少依赖项警告”的原因是,如果您在 useEffect 内部使用的任何变量在该组件内定义或作为道具传递给组件,则必须将其添加到依赖项数组中,否则反应警告你。这就是为什么您应该将 map 添加到数组中,并且由于您没有在 useEffect 内部更改它,因此不会导致重新渲染。

在这种情况下,您必须通过添加以下内容来告诉 es-lint 不要向我显示该警告://eslint-disable-next-line react-hooks/exhaustive-deps 因为您知道自己在做什么:

useEffect(() => {
   if (navigator.geolocation) {
      let latlng = currentPosition;
      const marker = L.marker(latlng,{ icon })
        .addTo(map)
        .bindPopup("Vous êtes ici.");
      map.panTo(latlng);

      navigator.geolocation.getCurrentPosition(function (position) {
        const pos = [position.coords.latitude,position.coords.longitude];
        setCurrentPosition(pos);
        marker.setLatLng(pos);
        map.panTo(pos);
      });
    } else {
      alert("Problème lors de la géolocalisation.");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    },[map]);
 

该注释将关闭对该行代码的依赖性检查。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res