我有一個簡單的 React 應用程式,它使用 Leaflet 和 OpenStreetMap 在地圖上顯示自行車站。
我已經獲取了所有經緯度,但是當我映射陣列并創建<Marker key={bike.id} position={[lat, long]}><Marker/>組件時,它們沒有出現在地圖上。
相反,我在瀏覽器控制臺上有這個警告:
will-change 記憶體消耗太高。預算限制是檔案表面積乘以 3(432150 像素)。超出預算的意愿變化將被忽略。
我看到了一些類似的問題和答案。這是因為 CSS 中會發生 will-change,但我使用的是 Leaflet 庫本身,所以我不知道在哪里解決這個問題。我也在 YouTube 上觀看了一些類似的視頻,即使我們的邏輯幾乎相同,它們也沒有任何問題。
MapComponent.jsx
import React, { useState } from 'react';
import '../styles/MapComponent.css';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import { useEffect } from 'react';
import { fetchUserData, fetchNetworks } from '../redux/action/';
import { useDispatch, useSelector } from 'react-redux'
const MapComponent = () => {
const dispatch = useDispatch()
const [latitude, setLatitude] = useState(0)
const [longitude, setLongitude] = useState(0)
const [checkCords, setCheckCords] = useState(false)
const countryCode = useSelector((state) => state.userData.country_code)
const bikeNetworks = useSelector((state) => state.bikeNetworks.networks)
const bikes = bikeNetworks.filter((network) => network.location.country == countryCode)
useEffect(() => {
if(navigator.geolocation) {
navigator.geolocation.watchPosition((position) => {
setLatitude(position.coords.latitude)
setLongitude(position.coords.longitude)
setCheckCords(true)
})
}
}, [])
useEffect(() => {
dispatch(fetchUserData())
dispatch(fetchNetworks())
}, [])
return (
!checkCords ? <h1>Loading...</h1> :
<MapContainer center={[latitude, longitude]} zoom={11}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[latitude, longitude]}>
<Popup>
A pretty CSS3 popup.<br /> Easily customizable.
</Popup>
</Marker>
{
bikes.map((bike) => {
<Marker
key={bike.id}
position={[bike.location.latitude, bike.location.longitude]}>
<Popup>
A pretty CSS3 popup.<br /> Easily customizable.
</Popup>
</Marker>
})
}
</MapContainer>
)
}
export default MapComponent
uj5u.com熱心網友回復:
您可能只是錯過了回呼中的一條return陳述句map,或者將其轉換為不帶花括號的短單運算式箭頭函式形式:
bikes.map((bike) => {
// Do not forget to `return` something
return (<Marker
key={bike.id}
position={[bike.location.latitude, bike.location.longitude]}>
<Popup>
A pretty CSS3 popup.<br /> Easily customizable.
</Popup>
</Marker>);
})
// Or a short arrow function that automatically returns the result of a single expression:
bikes.map((bike) => ( // No curly braces after the arrow
<Marker
key={bike.id}
position={[bike.location.latitude, bike.location.longitude]}>
<Popup>
A pretty CSS3 popup.<br /> Easily customizable.
</Popup>
</Marker>
))
有關 JavaScript 中箭頭函式語法的更多詳細資訊,請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions。
至于您的瀏覽器警告,很可能與您當前的問題無關。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433038.html
上一篇:使用反應鉤子的多步表單
