如何在React中防止在状态更改时重新加载Google地图?

huangapple go评论100阅读模式
英文:

How to stop reloading the google map when the state is changes in React?

问题

  1. 我有一个React应用其中包含一个Google地图组件
  2. 这个
  3. ```jsx
  4. <GoogleMap
  5. center={center}
  6. zoom={3}
  7. onLoad={(map) => setMap(map)}
  8. mapContainerStyle={{ width: '100%', height: '100%' }}
  9. >
  10. {data.toDisplayOnMap.length > 0 && (
  11. <>
  12. {data.toDisplayOnMap.map((element, i) => {
  13. if ('events' in element.item) {
  14. return <Marker key={i} position={element.item.locationCoords} onClick={() => navigate(`/location?id=${element.id}`)} icon={`http://labs.google.com/ridefinder/images/mm_20_red.png`} />
  15. } else if ('waypoints' in element.item) {
  16. if (element.item.traveltype === 'location') {
  17. return <DirectionsRenderer options={{ preserveViewport: true, polylineOptions: { strokeColor: 'blue', strokeWeight: 2 }, markerOptions: { icon: `http://labs.google.com/ridefinder/images/mm_20_yellow.png` } }} directions={element.route} />
  18. } else {
  19. let wps = element.item.waypoints;;
  20. let coords = [];
  21. wps.forEach((wp) => {
  22. wp.coords.forEach((coord) => {
  23. coords.push(coord)
  24. })
  25. })
  26. return (<>
  27. <Marker position={coords[0]} icon={`http://labs.google.com/ridefinder/images/mm_20_yellow.png`} />
  28. <Marker position={coords[coords.length - 1]} icon={`http://labs.google.com/ridefinder/images/mm_20_yellow.png`} />
  29. <Polyline path={coords} options={{ geodesic: true, strokeColor: '#000', strokeOpacity: 1, strokeWeight: 2, editable: false, draggable: false, clickable: true }} />
  30. </>)
  31. }
  32. }
  33. })}
  34. </>
  35. )}
  36. </GoogleMap>

发生的情况是,我有一个对象列表,如果人们选中复选框,则会显示在地图上,但我的中心在非洲,缩放为3,以便我可以看到大部分地图。如果我放大以查看那个标记或折线,然后取消选中复选框,它会重新加载地图并将我移回非洲。我真的不知道如何使用useMemo之类的东西,因为显示在我的地图上的内容来自页面的状态。我尝试过useMemo,但可能用错了,因为它什么都没做。而且在我的控制台中我有这个

  1. 253 useJsApiLoader.tsx:62 Performance warning! LoadScript has been reloaded unintentionally!

这是我声明地图的方式:
const [map, setMap] = useState(/** @type google.maps.Map */(null))

  1. const { isLoaded } = useJsApiLoader({
  2. googleMapsApiKey: ct.MAPS_API_KEY,
  3. libraries: p
  4. })

请帮我解决这个问题。

  1. <details>
  2. <summary>英文:</summary>
  3. I have a React app and I have a Google Map Component.
  4. This one:
  1. &lt;GoogleMap
  2. center={center}
  3. zoom={3}
  4. onLoad={(map) =&gt; setMap(map)}
  5. mapContainerStyle={{ width: &#39;100%&#39;, height: &#39;100%&#39; }}
  6. &gt;
  7. {data.toDisplayOnMap.length &gt; 0 &amp;&amp; (
  8. &lt;&gt;
  9. {data.toDisplayOnMap.map((element, i) =&gt; {
  10. if (&#39;events&#39; in element.item) {
  11. return &lt;Marker key={i} position={element.item.locationCoords} onClick={() =&gt; navigate(`/location?id=${element.id}`)} icon={`http://labs.google.com/ridefinder/images/mm_20_red.png`} /&gt;
  12. } else if (&#39;waypoints&#39; in element.item) {
  13. if (element.item.traveltype === &#39;location&#39;) {
  14. return &lt;DirectionsRenderer options={{ preserveViewport: true, polylineOptions: { strokeColor: &#39;blue&#39;, strokeWeight: 2 }, markerOptions: { icon: `http://labs.google.com/ridefinder/images/mm_20_yellow.png` } }} directions={element.route} /&gt;
  15. } else {
  16. let wps = element.item.waypoints;;
  17. let coords = [];
  18. wps.forEach((wp) =&gt; {
  19. wp.coords.forEach((coord) =&gt; {
  20. coords.push(coord)
  21. })
  22. })
  23. return (&lt;&gt;
  24. &lt;Marker position={coords[0]} icon={`http://labs.google.com/ridefinder/images/mm_20_yellow.png`} /&gt;
  25. &lt;Marker position={coords[coords.length - 1]} icon={`http://labs.google.com/ridefinder/images/mm_20_yellow.png`} /&gt;
  26. &lt;Polyline path={coords} options={{ geodesic: true, strokeColor: &#39;#000&#39;, strokeOpacity: 1, strokeWeight: 2, editable: false, draggable: false, clickable: true }} /&gt;
  27. &lt;/&gt;)
  28. }
  29. }
  30. })}
  31. &lt;/&gt;

)}

  1. &lt;/GoogleMap&gt;
  1. Well what is happening is I have a list of objects and if people are checking a Checkbox it is displayed on the map, but my center is in Africa and a zoom of 3 so I can get the most of the map. If I zoom in to see that Marker or that PolyLine and then I deselect the checkbox, it reloads the map and move me back to Africa. I don&#39;t really know how can I use this with a useMemo or something like that because What is displayed on my map it&#39;s coming from the state of the page. I tried useMemo, but probably I used it wrong because it was doing nothing. And also in my console I have this

253 useJsApiLoader.tsx:62 Performance warning! LoadScript has been reloaded unintentionally!

  1. This is how I declared my map:
  2. ` const [map, setMap] = useState(/** @type google.maps.Map */(null))`

const { isLoaded } = useJsApiLoader({
googleMapsApiKey: ct.MAPS_API_KEY,
libraries: p
})

  1. Please help me fix this.
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. 你可以使用React`useMemo`钩子来防止组件重新渲染。你可以这样使用`useMemo`
  6. ```jsx
  7. const renderGoogleMap = useMemo(() => {
  8. return <GoogleMap {...props} />;
  9. }, []);

然后调用这个记忆函数:

  1. <div>
  2. {renderGoogleMap}
  3. </div>

你也可以将依赖项传递给useMemo钩子,以在这些依赖项发生更改时允许重新渲染视图。

英文:

you can use react hook useMemo to prevent re-rendering of components. You can use useMemo this way

  1. const renderGoogleMap = useMemo(() =&gt; {
  2. return &lt;GoogleMap {...props} /&gt;;
  3. }, []);

and call this memoize function as

  1. &lt;div&gt;
  2. {renderGoogleMap}
  3. &lt;/div&gt;

you can also pass deps to useMemo hook on change of that deps you can allow to re-render the view.

huangapple
  • 本文由 发表于 2023年4月11日 12:52:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定