[英]Component re-renders wierdly on state change
My component with a simple MapBox gets re-rendered wierdly on every state change that has nothing to do with the component? 我的带有简单MapBox的组件会在与该组件无关的每个状态更改中被重新渲染。 Any idea how to prevent this?
任何想法如何防止这种情况?
It does not happen if I do not add the data
prop to the second argument of useEffect
, but I need this to re-render on an actual data change.. 如果我不将
data
useEffect
添加到useEffect
的第二个参数,则不会发生,但是我需要在实际数据更改时重新呈现它。
The map component: 地图组件:
const getMap = () => {
return new mapboxgl.Map({
container: 'mapContainer',
style: 'mapbox://styles/mapbox/light-v9',
center: [7.32, 60.44],
zoom: 6,
})
};
const Map = (props) => {
const { data } = props
if (data['features'] != null) {
useEffect(() => {
const map = getMap();
map.on('load', function () {
map.addSource('malls', {
type: "geojson",
data: data,
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
});
}, [data]); //
}
return (
<div style={style} id="mapContainer" />
);
}
Hooks should always be called outside conditionals, as mentioned in the Rules of Hooks . 挂钩应始终被称为条件挂钩,如《挂钩规则》所述 。 You can move your hook to the top-level and move the conditional inside the hook.
您可以将钩子移到顶层,并在钩子内部移动条件钩子。
const Map = (props) => {
const { data } = props
useEffect(() => {
if (data['features'] != null) {
const map = getMap();
map.on('load', function () {
map.addSource('malls', {
type: "geojson",
data: data,
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
});
}
}, [data]);
return (
<div style={style} id="mapContainer" />
);
}
与其将其编写为函数,不如使用一个类并实现shouldComponentUpdate
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.