问题描述
当我在 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
钩子中包含状态会导致无限循环的原因。
您需要确保不会发生这种情况!您有两个选择:
-
添加忽略评论并保持原样
-
创建一个额外的冗余变量来存储变量
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]);
,
为了便于理解,我先指出原因,然后再给出解决方案。
- 为什么?我对 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
使组件重新渲染 -> 无限循环
- 解决方案:
有一些解决方案:
- 通过在依赖项行正上方添加
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]);
该注释将关闭对该行代码的依赖性检查。