我的反應應用程式中有以下 map.jsx 檔案,它在螢屏上顯示地圖。我正在嘗試向此地圖添加一個標記(在一個名為“MyGreatPlace”的單獨組件中),它每 2 秒更改一次位置。它應該只更新標記而不是重繪 整個地圖,但是我收到以下錯誤:
Uncaught TypeError: setState is not a function
下面是我的代碼:
import GoogleMapReact from 'google-map-react';
import './map.css';
import MyGreatPlace from './my_great_place.jsx';
import React, { useEffect, useRef, useState, setState } from 'react';
const Map = ({ location, zoomLevel, markerLat, markerLong }) => {
useEffect(() => {
const interval = setInterval(() => {
changeMarkerLatitude();
}, 2000);
return () => clearInterval(interval);
}, []);
const changeMarkerLatitude = () => {
setState({
markerLat: markerLat 50,
});
};
return (
<div className='map'>
<div className='google-map'>
<GoogleMapReact
bootstrapURLKeys={{ key: 'KeyID' }}
defaultCenter={location}
defaultZoom={zoomLevel}>
<MyGreatPlace lat={markerLat} lng={markerLong} text={'A'} />
</GoogleMapReact>
</div>
</div>
);
};
export default Map;
有誰知道我可以如何解決這個錯誤,或者有沒有更新標記位置的替代方法?
uj5u.com熱心網友回復:
這不是您使用狀態物件的方式。useState 用于功能組件,您可以通過提供兩個值來呼叫它。首先是對實際值的參考,其次是對 setter 的參考。所以const [stateVal, setStateVal] = useState()給你一個狀態物件的未定義參考,以及一個更新它的函式的參考。你永遠不要直接改變狀態(例如 stateVal = newVal)。您總是使用 setter 來改變狀態(這會觸發重新渲染)。您始終可以通過將值傳遞給useState()呼叫來初始化該值。像這樣:setStateVal(newVal)
import GoogleMapReact from 'google-map-react';
import './map.css';
import MyGreatPlace from './my_great_place.jsx';
import React, { useEffect, useRef, useState, setState } from 'react';
const Map = ({ location, zoomLevel, markerLat, markerLong }) => {
const [markerLatVal, setMarkerLatVal] = useState(markerLat) // You can put value in here to initialize
useEffect(() => {
const interval = setInterval(() => {
changeMarkerLatitude();
}, 2000);
return () => clearInterval(interval);
}, []);
const changeMarkerLatitude = () => {
// 'prev' gives you access to the previous state value
setMarkerLatVal(prev => prev 50);
};
return (
<div className='map'>
<div className='google-map'>
<GoogleMapReact
bootstrapURLKeys={{ key: 'KeyID' }}
defaultCenter={location}
defaultZoom={zoomLevel}>
<MyGreatPlace lat={markerLat} lng={markerLong} text={'A'} />
</GoogleMapReact>
</div>
</div>
);
};
export default Map;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428639.html
標籤:javascript html 反应 谷歌地图 api-3 谷歌地图标记
下一篇:更改html頁面中的值src
