我有一个map box react组件,它通过带有lng和lat Cordinates道具来接收猫对象。
<MapContainer cats={cats} /> ----- This is component below
componentDidMount() {
const map = new mapboxgl.Map({
container: this.mapContainer,
style: 'mapbox://styles/mapbox/streets-v11',
center: [this.state.lng, this.state.lat],
zoom: this.state.zoom
});
map.on('move', () => {
this.setState({
lng: map.getCenter().lng.toFixed(4),
lat: map.getCenter().lat.toFixed(4),
zoom: map.getZoom().toFixed(2)
});
});
//var marker = new mapboxgl.Marker()
//.setLngLat([12.550343, 55.665957])
//.addTo(map);
this.props.cats.map((cat) => {
console.log('test');
var marker = new mapboxgl.Marker()
.setLngLat([cat.lat, cat.lng])
.addTo(this.map);
});
}
代码中注释掉的部分添加了一个映射标记,而不是按照教程执行。
但是,在下面的代码中,我试图通过我的cat props对象进行映射以添加多个标记,但是console.log('test'); 没有出现在控制台中,所以我一定是做错了什么。
已经有一段时间了,我做了一些反应,请给我指出正确的方向?! :)
已修复:
cats在componentDidMount()中是空的,所以我将代码移到componentWillReceiveProps()中,这就修复了它! :)
问题是您的cats在组件挂载时不可用,但在以后可用,这就是为什么它们出现在render中,但在componentdidmount
期间有一个空数组可用的原因。
您需要添加您的标记后,您的猫可用。 您可以移动逻辑以添加ComponentDidUpdate()
生命周期钩子,并添加如下所示的检查。
componentDidUpdate(prevProps) {
// Handle your condition here, something like below
// Make sure to add a condition to run only when required, because componentDidUpdate will run each time prop or state has changed.
if(this.props.cat.length > 0 && this.props.cat !== prevProps.cat ) {
// Your marker logic
}
}