在 useEffect 返回数据之前加载 Mapbox 地图 [英] Mapbox map is getting loaded before useEffect returns data

查看:72
本文介绍了在 useEffect 返回数据之前加载 Mapbox 地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习反应钩子,我想在初始渲染时使用从后端获得的坐标加载地图,但不知何故,我的地图在我的 api 返回数据之前就被渲染了,我如何确保我的地图会等到数据返回?我需要为此设置任何条件吗?

下面是api代码

import React, { useState, useEffect, useRef } from "react";import { useDispatch, useSelector } from 'react-redux';从'mapbox-gl'导入mapboxgl;从'./features/counter/getInfo/getDetails.js'导入{getBikeInfo,mapDetails}功能应用(){const dispatch = useDispatch();const dataToDisplay = useSelector(mapDetails);const mapContainer = useRef(null);mapboxgl.accessToken = 'pk.eyJ1IjoidmloYW5nMTYiLCJhIjoiY2ttOHowc2ZhMWN2OTJvcXJ0dGpiY21pNyJ9.hK5Wxwby89E7tKWoBoY5bg';useEffect(() => {调度(getBikeInfo())var map = new mapboxgl.Map({容器:mapContainer.current,样式:'mapbox://styles/mapbox/light-v10',中心:[-96, 37.8],变焦:3});console.log('mapdetails:' + mapDetails)console.log('数据显示:' + dataToDisplay)map.on('加载', 函数 () {//添加图像以用作自定义标记地图.loadImage('https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',功能(错误,图像){如果(错误)抛出错误;map.addImage('自定义标记', 图像);//添加一个带有 2 个点的 GeoJSON 源map.addSource('点', {'type': 'geojson','数据': {'type': '功能集合',功能":dataToDisplay}});//添加符号层地图.addLayer({'id': '点','类型':'符号','来源':'点','布局': {'icon-image': '自定义标记',//从源的标题"中获取标题名称;财产'文本字段': ['get', 'title'],'文本字体':['打开 Sans Semibold','Arial Unicode MS Bold'],'文本偏移':[0, 1.25],'文本锚':'顶部'}});});});}, []);返回 (<div className="district-map-wrapper"><div id="districtDetailMap";className=地图"><div style={{ height: "100%";}} ref={mapContainer}>

);}导出默认应用程序;

以下是我更新的代码:

useEffect(() => {如果 (dataToDisplay.length != 0) {加载地图}}, []);

但经过一些刷新后,我看到数据没有被填充并将 dataDisplay 设置为 [].

更新1:根据建议,我已经像这样更新了我的代码

if(!dataLoaded) {//如果你还没有准备好,不要渲染任何东西返回 (<div className="隐藏"><div id="districtDetailMap";className=地图"><div style={{ height: "100%";}} ref={mapContainer}>

);}

其中 className="hidden" 在 App.css 中定义如下

.hidden{显示:无;}

但我仍然遇到同样的问题

根据要求 PFB 我的沙箱链接

<块引用>

codesandbox

解决方案

由于您使用了 useEffect,因此您基本上可以保证您的组件在启动查询之前会渲染一次

如果您想确保您的组件不会被渲染,请使用一些标志来指示数据已准备就绪,在您设置 Map 并有条件地渲染一些后备 ui 后将其设置为 true这个标志是 false

function App() {const [dataLoaded, setDataLoaded] = useState(false);//引入标志const dispatch = useDispatch();const dataToDisplay = useSelector(mapDetails);const mapContainer = useRef(null);mapboxgl.accessToken = 'pk.eyJ1IjoidmloYW5nMTYiLCJhIjoiY2ttOHowc2ZhMWN2OTJvcXJ0dGpiY21pNyJ9.hK5Wxwby89E7tKWoBoY5bg';useEffect(() => {调度(getBikeInfo())var map = new mapboxgl.Map({容器:mapContainer.current,样式:'mapbox://styles/mapbox/light-v10',中心:[-96, 37.8],变焦:3});console.log('mapdetails:' + mapDetails)console.log('数据显示:' + dataToDisplay)map.on('加载', 函数 () {//添加图像以用作自定义标记地图.loadImage('https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',功能(错误,图像){如果(错误)抛出错误;map.addImage('自定义标记', 图像);//添加一个带有 2 个点的 GeoJSON 源map.addSource('点', {'type': 'geojson','数据': {'type': '功能集合',功能":dataToDisplay}});//添加符号层地图.addLayer({'id': '点','类型':'符号','来源':'点','布局': {'icon-image': '自定义标记',//从源的标题"中获取标题名称;财产'文本字段': ['get', 'title'],'文本字体':['打开 Sans Semibold','Arial Unicode MS Bold'],'文本偏移':[0, 1.25],'文本锚':'顶部'}});设置数据加载(真);//完成后将其设置为 true});});}, []);返回 (<div className="district-map-wrapper";样式={数据加载?未定义:{显示:'无'}}><div id="districtDetailMap";className=地图"><div style={{ height: "100%";}} ref={mapContainer}>

);}

I have started learning react hooks and I want to load map on initial render with cooridnates which I get from the backend, but somehow my map is getting rendered before my api give the data back, how do I make sure my map will wait till data is return ? do I need to put any condition on that?

below is api code

import React, { useState, useEffect, useRef } from "react";
import { useDispatch, useSelector } from 'react-redux';
import mapboxgl from 'mapbox-gl';
import { getBikeInfo, mapDetails } from './features/counter/getInfo/getDetails.js'

function App() {
    const dispatch = useDispatch();

    const dataToDisplay = useSelector(mapDetails);
    
    const mapContainer = useRef(null);

    mapboxgl.accessToken = 'pk.eyJ1IjoidmloYW5nMTYiLCJhIjoiY2ttOHowc2ZhMWN2OTJvcXJ0dGpiY21pNyJ9.hK5Wxwby89E7tKWoBoY5bg';

    useEffect(() => {
        dispatch(getBikeInfo())

        var map = new mapboxgl.Map({
            container: mapContainer.current,
            style: 'mapbox://styles/mapbox/light-v10',
            center: [-96, 37.8],
            zoom: 3
        });

        console.log('mapdetails:' + mapDetails)
        console.log('data display:' + dataToDisplay)
        
        map.on('load', function () {
            // Add an image to use as a custom marker
            map.loadImage(
                'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
                function (error, image) {
                    if (error) throw error;
                    map.addImage('custom-marker', image);
                    // Add a GeoJSON source with 2 points
                    map.addSource('points', {
                        'type': 'geojson',
                        'data': {
                            'type': 'FeatureCollection',
                            'features': dataToDisplay
                        }
                    });

                    // Add a symbol layer
                    map.addLayer({
                        'id': 'points',
                        'type': 'symbol',
                        'source': 'points',
                        'layout': {
                            'icon-image': 'custom-marker',
                            // get the title name from the source's "title" property
                            'text-field': ['get', 'title'],
                            'text-font': [
                                'Open Sans Semibold',
                                'Arial Unicode MS Bold'
                            ],
                            'text-offset': [0, 1.25],
                            'text-anchor': 'top'
                        }
                    });
                }
            );
        });
    }, []);


    return (
        <div className="district-map-wrapper">
            <div id="districtDetailMap" className="map">
                <div style={{ height: "100%" }} ref={mapContainer}>

                </div>
            </div>
        </div>
    );
}

export default App;

below is my updated code:

useEffect(() => {
    if (dataToDisplay.length != 0) {
        loadtheMap
    }
}, []);

but after some refresh I see data is not getting populated and setting dataDisplay to [].

update 1: based on suggestion I have updated my code like this

if(!dataLoaded) { // do not render anything if you're not ready
  return ( 
  <div className="hidden">
  <div id="districtDetailMap" className="map">
      <div style={{ height: "100%" }} ref={mapContainer}>

      </div>
  </div>
</div>);
}

where className="hidden" is define in App.css like below

.hidden{
  display: none;
}

but still I am on same issue

as requested PFB my sandbox link

codesandbox

解决方案

Since you're using useEffect you are basically guaranteed that your component will render once before it even initiates the query

If you want to ensure your component won't be rendered, use some flag to indicate that data is ready, set it to true after you set up your Map and conditionally render some fallback ui while this flag is false

function App() {
    const [dataLoaded, setDataLoaded] = useState(false); // introduce the flag
    const dispatch = useDispatch();

    const dataToDisplay = useSelector(mapDetails);
    
    const mapContainer = useRef(null);

    mapboxgl.accessToken = 'pk.eyJ1IjoidmloYW5nMTYiLCJhIjoiY2ttOHowc2ZhMWN2OTJvcXJ0dGpiY21pNyJ9.hK5Wxwby89E7tKWoBoY5bg';

    useEffect(() => {
        dispatch(getBikeInfo())

        var map = new mapboxgl.Map({
            container: mapContainer.current,
            style: 'mapbox://styles/mapbox/light-v10',
            center: [-96, 37.8],
            zoom: 3
        });

        console.log('mapdetails:' + mapDetails)
        console.log('data display:' + dataToDisplay)
        
        map.on('load', function () {
            // Add an image to use as a custom marker
            map.loadImage(
                'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
                function (error, image) {
                    if (error) throw error;
                    map.addImage('custom-marker', image);
                    // Add a GeoJSON source with 2 points
                    map.addSource('points', {
                        'type': 'geojson',
                        'data': {
                            'type': 'FeatureCollection',
                            'features': dataToDisplay
                        }
                    });

                    // Add a symbol layer
                    map.addLayer({
                        'id': 'points',
                        'type': 'symbol',
                        'source': 'points',
                        'layout': {
                            'icon-image': 'custom-marker',
                            // get the title name from the source's "title" property
                            'text-field': ['get', 'title'],
                            'text-font': [
                                'Open Sans Semibold',
                                'Arial Unicode MS Bold'
                            ],
                            'text-offset': [0, 1.25],
                            'text-anchor': 'top'
                        }
                    });
                    setDataLoaded(true); // set it to true when you're done
                }
            );
        });
    }, []);

    return (
        <div className="district-map-wrapper" style={dataLoaded ? undefined : {display: 'none'}}>
            <div id="districtDetailMap" className="map">
                <div style={{ height: "100%" }} ref={mapContainer}>

                </div>
            </div>
        </div>
    );
}

这篇关于在 useEffect 返回数据之前加载 Mapbox 地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆