React Hook useEffect缺少依赖项.要么包含它们,要么删除依赖数组react-hooks/精疲力竭-de



当我加载我的React应用程序时,我得到这个警告:

React Hook useEffect缺少依赖项:'props.maxEast',的道具。maxNorth"、"道具。maxSouth'和'props.maxWest'。要么包括它们或删除依赖项数组react-hooks/exhaustive-deps

我一直无法找到消除此警告的解决方案。上面的四个道具是Map组件的道具,useEffect函数就驻留在这个组件中。当用户在应用程序中执行搜索时,useEffect函数在地图上绘制一个边界框。

useEffect(() => {
if (!map.current) return; // wait for map to initialize
// Check if Mapbox GL styles have loaded
var check = checkIfMapboxStyleIsLoaded(map.current);
if(check) {
console.log("A load event occurred!");
if(props.show) {
map.current.addSource('newroute', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': 
[
[props.maxEast, props.maxNorth],
[props.maxEast, props.maxSouth],
[props.maxWest, props.maxSouth],
[props.maxWest, props.maxNorth],
[props.maxEast, props.maxNorth]
]
}
}
});

// Draws bounding box
map.current.addLayer({
'id': 'newroute',
'type': 'line',
'source': 'newroute',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#ff0000',
'line-width': 5
}
}); 

}
else if (map.current.getLayer('newroute')) {
map.current.removeLayer('newroute');
map.current.removeSource('newroute');
}
}
}, [props.show]);

实际上,使用效果预期可能的状态和道具变量作为它的依赖数组,因为它已经为它定义了eslint规则。

useEffect感知到你有许多道具变量,但你只使用1 (props.show)在依赖数组。这就是为什么它建议警告添加全部或删除它们。

<<p>

解决方案/strong>*

1-要么在依赖数组中添加所有的道具,如[props]。表演,道具。隐藏……等)

*

2-或者您可以通过在依赖数组之前添加这一行来忽略此警告。

useEffect(()=>{
// eslint-disable-next-line react-hooks/exhaustive-deps
},[props.show])

你给你的UseEffect()附加了一个props而不是State值。

要触发UseEffect()事件,你需要给它附加一个这样的状态:

[show, setShow] = useState(true);
useEffect(() => {
// do stuff
}, [show]);

相关内容

最新更新