在映射标记数组之前,reactjs nullcheck

时间:2017-10-18 14:34:54

标签: javascript reactjs google-maps ecmascript-6

您好我试图通过一系列标记进行映射,但第一个对象是空的。如何在JSX中创建Nullcheck,以便只有标记出现在地图上并非空。 该函数位于const GettingStartedGoogleMap

const GettingStartedGoogleMap = withGoogleMap(props =>(
    <GoogleMap
      defaultZoom={13}
      center={props.center}
      >
      {if(props.markers !== undefined && props.markers != null && props.markers.length > 0)
        {props.markers.map(marker => (
          <InfoWindow  position={{ lat: marker.latitude, lng: marker.longitude }}
          key={marker.id}>
              <div>
              {marker.price}
              </div>
          </InfoWindow>
        ))}
      }
</GoogleMap>
));

export class AppMap extends Component {

 constructor(props) {
   super(props);
   this.Ref = firebase.database().ref().child('app').child('cards');
   this.state = ({
     markers : [{
       latitude: "",
       longitude: "",
       price: "",
       id: ""
     }]
   })
 }

 componentWillUpdate (){
   const previousMarker = this.state.markers;
   this.Ref.orderByChild('address').equalTo(this.props.city)
      .on('child_added', snap => {
      previousMarker.push({
        latitude: snap.node_.children_.root_.right.left.value.children_.root_.left.value.value_,
        longitude: snap.node_.children_.root_.right.left.value.children_.root_.value.value_,
        price: snap.node_.children_.root_.value.value_,
        key: snap.key + "_Marker",

        })

        console.log(previousMarker)

      })
 }


     render() {
         return (
             <div style={{height: `400px`}}>
                 <GettingStartedGoogleMap
                 containerElement={
                <div style={{ height: `100%` }} />
              }
              mapElement={
                <div style={{ height: `100%` }} />
              }

              center={this.props.center}
              markers={this.state.markers}

              googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
              />
            </div>
         );
     }
   }

1 个答案:

答案 0 :(得分:0)

您可以使用&&运算符检查Falsy values

const GettingStartedGoogleMap = withGoogleMap(props => (
    <GoogleMap
        defaultZoom={13}
        center={props.center}
    >
        {
            props.markers && props.markers.map(marker => {
                return marker && (
                    <InfoWindow position={{ lat: marker.latitude, lng: marker.longitude }}
                        key={marker.id}>
                        <div>
                            {marker.price}
                        </div>
                    </InfoWindow>
                )
            })
        }
    </GoogleMap>
));