【发布时间】: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 我的沙盒链接
【问题讨论】:
标签: reactjs react-redux react-hooks