我正在使用react-redux-mapbox-gl库。我想要映射一系列斑点,以便在Mapbox组件中创建多个叠加组件。但是在尝试映射数组时,我总是得到一个未定义的错误。我是React / Redux的新手,所以我不确定是什么问题。
我的组件下面:
import React from 'react';
import Mapbox from 'react-redux-mapbox-gl';
import SpotsOverlay from './SpotsOverlay'
const mapStateToProps = state => ({
spots: state.homemap.spots
})
class HomeMap extends React.Component {
render(){
return (
<Mapbox
mapboxgl={mapboxgl}
accessToken={mapAccessToken}
getMap={this.getMap}
style={this.mapStyle}
options={this.mapOptions}
>
{
this.props.spots.map(spot =>{
return (
<SpotsOverlay
overlay={this.overlay}
key={spot.id}/>
);
})
}
</Mapbox>
);
}
}
答案 0 :(得分:0)
返回方法之外的映射可能会有所帮助。
class HomeMap extends React.Component {
render(){
let spots = [];
if(this.props.spots) {
spots = this.props.spots.map(spot =>{
return (
<SpotsOverlay
overlay={this.overlay}
key={spot.id}/>
);
});
}
return (
<Mapbox
mapboxgl={mapboxgl}
accessToken={mapAccessToken}
getMap={this.getMap}
style={this.mapStyle}
options={this.mapOptions}
>
{spots}
</Mapbox>
);
}
}
正如@MayankShukla在评论中所说,其效果更好的原因是
最初的reducer状态是{},所以state.homemap.spots将是未定义的,当你使用undefined的地图时