如果只有部分状态发生变化,有没有办法停止重新渲染?
问题是每次我将鼠标悬停在标记上时,都会打开或关闭一个弹出窗口,它会导致所有标记重新渲染,即使mystate没有改变只是activePlace状态正在改变。console.log(myState);每次我在标记内外徘徊时都在运行。
我尝试使用 useMemo 钩子,但不知道如何使用它。有什么帮助吗?
这是我的代码:
import React, { useEffect, useState } from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';
import { Icon } from 'leaflet';
const myicon = new Icon({
iconUrl: './icon.svg',
iconSize: [20, 20]
});
const MyMap = () => {
const [myState, setMyState] = useState(null);
const [activePlace, setActivePlace] = useState(null);
const getData = async () => {
let response = await axios
.get('https://corona.lmao.ninja/v2/jhucsse')
.catch(err => console.log(err));
let data = response.data;
setMyState(data);
// console.log(data);
};
useEffect(() => {
getData();
}, []);
if (myState) {
console.log(myState);
return (
<Map
style={{ height: '100vh', width: '100vw' }}
center={[14.561, 17.102]}
zoom={1}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>'
url={
'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'
}
/>
{myState.map(country => {
return (
<Marker
key={uuidv4()}
position={[
country.coordinates.latitude,
country.coordinates.longitude
]}
onmouseover={() => {
setActivePlace(country);
}}
onmouseout={() => {
setActivePlace(null);
}}
icon={myicon}
/>
);
})}
皈依舞
相关分类