【问题标题】:react-google-maps/api Avoiding re-render of Map after some state changesreact-google-maps/api 在某些状态更改后避免重新渲染地图
【发布时间】:2021-02-20 20:01:36
【问题描述】:

我遇到了一些问题,我的 GoogleMaps 实例会刷新并自行以某个 onClick 函数为中心,在该函数中设置状态并且会发生整个组件渲染周期。

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

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 经验,感谢任何帮助!

【问题讨论】:

    标签: javascript reactjs jsx react-google-maps


    【解决方案1】:

    我使用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() 函数中进行渲染:

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 1970-01-01
      • 2020-07-07
      • 2018-12-21
      • 2018-10-15
      • 1970-01-01
      • 2020-04-07
      • 2017-03-26
      • 2015-09-08
      相关资源
      最近更新 更多