【问题标题】:Mapbox map is getting loaded before useEffect returns dataMapbox 地图在 useEffect 返回数据之前被加载
【发布时间】:2021-03-16 07:51:10
【问题描述】:

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

下面是api代码

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;

下面是我更新的代码:

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

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

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

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>);
}

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

.hidden{
  display: none;
}

但我仍然在同一个问题上

根据要求 PFB 我的沙盒链接

codesandbox

【问题讨论】:

    标签: reactjs react-redux react-hooks


    【解决方案1】:

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

    如果您想确保您的组件不会被渲染,请使用一些标志来指示数据已准备好,在您设置地图后将其设置为true,并在此标志为@987654323 时有条件地渲染一些备用用户界面@

    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>
        );
    }
    

    【讨论】:

    • 我想设置 dataToDisplay 然后加载时的条件,我应该怎么做?我添加了 if(dataToDisplay){ load} 但它不起作用
    • ok..我这样添加 if(dataToDisplay.length != 0){ load }it works
    • 再次重新加载后我面临同样的问题
    • 我已经用代码示例更新了答案,我认为可以帮助你
    • ** if(!dataLoaded) { // 如果你还没准备好就不要渲染任何东西 return null; }** 添加此行后,我收到此错误 Invalid type: 'container' must be a String or HTMLElement. at const [dataLoaded, setDataLoaded] = useState(false);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2018-10-10
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多