api避免在某些状态更改后重新渲染地图

api避免在某些状态更改后重新渲染地图

本文介绍了react-google-maps/api避免在某些状态更改后重新渲染地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题,我的GoogleMaps实例将刷新并自动将自身置于某些onClick函数上,该函数设置了状态,并且整个Component渲染周期都会发生.

I was having problems where my GoogleMaps instance would refresh and self center itself on some onClick function where the state was being set and the entire Component rendering cycle would happen.

在进行一些谷歌搜索之后,建议将组件实例化分离并重新使用.现在的问题是,我有一些逻辑来显示<GoogleMaps>组件内的标记,该标记不再按预期工作,并且我不知道如何重构:

After some Googling it was suggested that the component instantiation be separated and re-used. The problem now is I have some logic to display markers inside <GoogleMaps> component that is no longer working as expected and I don't know how to refactor:

export default function LocationSearchResults({
    ...
    }) {
    const [map, setMap] = useState(null)
    const [markersContainer, setMarkersContainer] = useState([])

    const getMap = () => {

        if (map) {
            return map;
        } else {
            setMap(<GoogleMap mapContainerStyle={containerStyle}
                options={ {
                        minZoom: 3,
                        maxZoom: 15
                    }}
                center={{
                        lat: 49.25,
                        lng: -84.5
                    }}
                zoom={5}
                onLoad={onLoad}
                onDragEnd={onDragEnd} >
                {
                    markersContainer.map(place => { //Only executes once? Does not listen for changes
                        return (< Marker key={place.id}
                            position={ place.position}
                        />
                        )
                    })

                }

                </GoogleMap>

                )

                return map

            }
        }

        render( <div className="..." >
                    {
                     getMap()
                    }
            </div>
        )
    }

我没有大量的React使用经验,非常感谢您的帮助!

I don't have a ton of experience with React, any help is appreciated thanks!

推荐答案

我使用useMemo

...instantiate all event listener functions here

const map = useMemo(() =>
 {
   return (<GoogleMap
    mapContainerStyle={containerStyle}
    options={{ minZoom: 3, maxZoom: 15 }}
    center={{
      lat: 49.25,
      lng: -84.5
    }
    }
    zoom={5}
    onLoad={onLoad}
    onDragEnd={onDragEnd}
  // onUnmount={onUnmount}
  >
     {markersContainer.map(place => { return ( <Marker
                    key={place.id}
                    position={place.position} />
                    )
                   })
    }
 </GoogleMap>)

}, [markersContainer])

然后我只需在我的render()函数中进行渲染:

then I simply render in my render() function:

return (
    <>
<div>...
  {map}
</div>
</>)

除非添加/删除了新标记,否则不再进行不必要的刷新.

No more unnecessary refreshes unless new markers are added/removed.

这篇关于react-google-maps/api避免在某些状态更改后重新渲染地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:04