React 中的 Mapbox 没有 Class 个组件

Mapbox in React without Class Components

我正在尝试将 MapBox-GL 与 React 结合使用。我试图避免使用包装器。

我已经使用 Class 组件成功创建了地图,但想将其转换为仅使用函数来利用挂钩。在函数中显示地图效果很好:

const map = () => {
    new mapboxgl.Map({
    container: 'mapContainer',
    style: 'mapbox://styles/mapbox/light-v9',
    center: [7.32, 60.44],
    zoom: 6,
    })
};
const Map = () => {
    const style = {
        position: 'absolute',
        top: 0,
        bottom: 0,
        width: '100%',
        height: '100vh'
    };
    useEffect(()=>{
        map();

    });


    return (
        <Row type="flex" gutter="50">
            <Col xs={{ span: 18 }}>
                <div style={style} id="mapContainer" />
            </Col>
        </Row>
    );
}

但是,我想添加控制器并使用地图进行操作。我通常在 ComponentDidMount() 中执行此操作。

我已经尝试将 map.addControl(geocoder); 添加到 useEffect 以及 Map 函数之外。我只收到错误:

TypeError: map.addControl is not a function

componentDidMount 的对应项是 useEffect,输入为零。

map.addControl(geocoder) 假设 mapMap 的一个实例,而它是一个函数,而不是 return 一个值。

应该是:

const getMap = () => {
    return new mapboxgl.Map({ ... })
};

const Map = () => {
    useEffect(()=>{
        const map = getMap();
        map.addControl(geocoder);
    }, []);
    ...
};