React map redux state 在一个组件内创建多个组件

React map redux state to create multiple components within a component

我正在使用 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>
  );
}
}

在 return 方法之外进行映射可能会有帮助。

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 在他的评论中所说,这种效果更好的原因是

initially reducer state is {}, so state.homemap.spots will be undefined and when you were using map of undefined