我是 React 和开发 covid-19 跟踪器应用程序的新手。我有一个国家/地区下拉列表,当我们从下拉列表中选择任何国家/地区时,会进行 api 调用,并使用 react hooks(useState) 显示电晕病例、死亡病例和康复病例。这是使用 onCountryChange 函数发生的;
const onCountryChange = async (event) => {
const countryCode = event.target.value;
setCountry(countryCode);
const url =
countryCode === 'worldwide'
? 'https://disease.sh/v3/covid-19/all'
: `https://disease.sh/v3/covid-19/countries/${countryCode}`;
await fetch(url)
.then((response) => response.json())
.then((data) => {
setCountry(countryCode);
setCountryInfo(data);
setMapCenter([data.countryInfo.lat, data.countryInfo.long]);
setMapZoom(4);
});
};
我已经带来了react传单图并有一个状态
[ mapCenter, setMapCenter ] = useState({lat: 34.80746, lng: -40.4796})
现在在 onCountryChange 我正在设置 setMapCenter([data.countryInfo.lat, data.countryInfo.long]);但地图并未以所选国家/地区为中心。任何人都可以帮助我这里有什么问题。 这是 gitup 存储库。
https://github.com/sohailshams/covid-19-tracker
答案 0 :(得分:0)
首先,您每次提出请求时都不会更改纬度坐标。
const onCountryChange = async (event) => {
const countryCode = event.target.value;
setCountry(countryCode);
const url =
countryCode === "worldwide"
? "https://disease.sh/v3/covid-19/all"
: `https://disease.sh/v3/covid-19/countries/${countryCode}`;
await fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
setCountryInfo(countryCode);
setCountryInfo(data);
const {
countryInfo: { lat, long },
} = data;
setMapCenter({ lat, lng: long }); // here change the coordinates of the selected country
});
};
第二,使用组件通过将新坐标作为道具传递来更改地图视图,因为更改中心是不够的,因为它在 3.x 版本上不可变
function ChangeMapView({ coords }) {
const map = useMap();
map.setView([coords.lat, coords.lng], map.getZoom());
return null;
}
并在您的 Map 组件中使用它:
function Map({ center, zoom }) {
return (
<div className='map'>
<LeafletMap center={center} zoom={zoom}>
<TileLayer
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<ChangeMapView coords={center} /> //here use it by passing the center coords
</LeafletMap>
</div>
);
}
编辑
这是一个demo
我明确使用你的github代码来重现问题,后来 我看到您对代码进行了一些更改。 通过使用这一行
setMapCenter([data.countryInfo.lat, data.countryInfo.long]);
您正在更改变量的类型,它最初是一个对象,突然间它变成了一个数组。在我看来,你不应该这样做。但最后如果你想这样做,只需稍微改变 ChangeMapView comp 为
function ChangeMapView({ coords }) {
const map = useMap();
map.setView([coords[0], coords[1], map.getZoom());
return null;
}
您的问题再次得到解决