我正在 NextJS 应用程序中使用 GoogleMap 来处理地图。下面是显示地图的组件。
它基本上按照我的预期工作。
function Map({latitude,longitude}:
{latitude:number,longitude:number}) {
const center = useMemo(() => ({
lat: latitude,
lng: longitude
}), []);
return (
<GoogleMap zoom={17} center={center}
mapContainerClassName="map-container">
<Marker position={center} />
</GoogleMap>
);
} /* End of Map */
上面的组件在另一个组件中使用:
export default function GeoMap(
{shop,gps}:
{shop: string, gps: string;}
) {
const [theGPS, setTheGPS] =
useState({coords:{latitude:0.0,longitude:0.0}})
const [theLatitude, setLatitude] = useState(0.0)
const [theLongitude, setLongitude] = useState(0.0)
const dbRef = ref(firebaseDatabase, 'MyApp/'+shop)
useEffect(() => {
onValue(dbRef, (snapshot) => {
const coordsStr = snapshot.child('gPS').val().split(','),
latit = parseFloat(coordsStr[0]),
longit = parseFloat(coordsStr[1])
console.log('shop='+shop)
console.log('coordsStr='+coordsStr)
console.log('latit='+latit.toString())
console.log('longit='+longit.toString())
setTheGPS({coords: {latitude:latit, longitude:longit}})
setLatitude(latit); setLongitude(longit)
}, (error) => {
console.log('Error(onValue): '+error);
});
}, [])
useEffect(() => { // Not needed. Just for test.
setLatitude(theGPS.coords.latitude);
setLongitude(theGPS.coords.longitude)
}, [theGPS])
.....
return <Map latitude= {theLatitude}
longitude= {theLongitude} />
} /* End of GeoMap */
但是我有以下问题:
当纬度和经度的值发生变化(由于某些外部操作)时,我可以在日志中看到它按预期发生,但地图中的显示没有更新。这是为什么?
如果我手动重新加载页面,我当然可以看到地图充分更新;但我想让地图自行更新,而不必手动重新加载。由于纬度和经度是状态变量,我希望地图能够自动更新。
我设法使用存根重现该问题
GoogleMap
。在 useMemo
组件中添加对 Map
的依赖后,问题得到解决:
const center = useMemo(() => ({
lat: latitude,
lng: longitude
}), [latitude, longitude]);
这是我用来重现的其余代码:
export function GeoMap() {
const [theGPS, setTheGPS] =
useState({coords:{latitude:0.0,longitude:0.0}})
const [theLatitude, setLatitude] = useState(0.0)
const [theLongitude, setLongitude] = useState(0.0)
useEffect(() => { // Not needed. Just for test.
setLatitude(theGPS.coords.latitude);
setLongitude(theGPS.coords.longitude)
}, [theGPS])
return <div>
<button onClick={() => {
console.log('Clicked')
setLatitude(theLatitude + 1)
setLongitude(theLongitude + 1)
}}>render</button>
<Map latitude= {theLatitude}
longitude= {theLongitude} />
</div>
}
function Map({latitude,longitude}:
{latitude:number,longitude:number}) {
// THE FIX
const center = useMemo(() => ({
lat: latitude,
lng: longitude
}), [latitude, longitude]);
// PREVENTS RERENDER
// const center = useMemo(() => ({
// lat: latitude,
// lng: longitude
// }), []);
return <GoogleMap center={center} zoom={17}/>
}
function GoogleMap({center, zoom }: {center: {lat:number,lng:number}, zoom: number}) {
return <div>
<div>{center.lat}</div>
<div>{center.lng}</div>
</div>
}