Fix usage with function refs (#1339)

This commit is contained in:
Xiaoji Chen 2021-02-06 18:30:43 -08:00 committed by Xiaoji Chen
parent 28eba1151e
commit fa6601e8fc
2 changed files with 15 additions and 9 deletions

View File

@ -1,5 +1,5 @@
import * as React from 'react';
import {useContext, useRef, useMemo, useEffect, forwardRef} from 'react';
import {useContext, useRef, useMemo, useEffect, useImperativeHandle, forwardRef} from 'react';
import * as PropTypes from 'prop-types';
import StaticMap from './static-map';
@ -270,6 +270,13 @@ function onPointerClick(event) {
}
/* End of event handers */
function getRefHandles(staticMapRef) {
return {
getMap: staticMapRef.current && staticMapRef.current.getMap,
queryRenderedFeatures: staticMapRef.current && staticMapRef.current.queryRenderedFeatures
};
}
/* eslint-disable max-statements */
const InteractiveMap = forwardRef((props, ref) => {
const parentContext = useContext(MapContext);
@ -283,7 +290,7 @@ const InteractiveMap = forwardRef((props, ref) => {
[]
);
const eventCanvasRef = useRef(null);
const staticMapRef = ref || useRef(null);
const staticMapRef = useRef(null);
// Event handlers are registered once but need access to the latest props
// This is an anti-pattern, though it maintains a persistent reference to the latest props/state of this component
@ -324,6 +331,8 @@ const InteractiveMap = forwardRef((props, ref) => {
}
};
useImperativeHandle(ref, () => getRefHandles(staticMapRef), []);
const context = useMemo(
() => ({
...parentContext,

View File

@ -18,7 +18,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import * as React from 'react';
import {useState, useRef, useContext, useMemo, useImperativeHandle, forwardRef} from 'react';
import {useState, useRef, useContext, useImperativeHandle, forwardRef} from 'react';
import * as PropTypes from 'prop-types';
import WebMercatorViewport from 'viewport-mercator-project';
@ -101,13 +101,13 @@ function NoTokenWarning() {
}
function getRefHandles(mapboxRef) {
return () => ({
return {
getMap: () => mapboxRef.current && mapboxRef.current.getMap(),
queryRenderedFeatures: (geometry, options = {}) => {
const map = mapboxRef.current && mapboxRef.current.getMap();
return map && map.queryRenderedFeatures(geometry, options);
}
});
};
}
function preventScroll(event) {
@ -182,10 +182,7 @@ const StaticMap = forwardRef((props, ref) => {
// External apps can call methods via ref
// Note: this is not a recommended pattern in React FC - Keeping for backward compatibility
useImperativeHandle(
ref,
useMemo(() => getRefHandles(mapboxRef), [])
);
useImperativeHandle(ref, () => getRefHandles(mapboxRef), []);
const overlays = map && (
<MapContextProvider