2

我需要为地图中的每个标记创建一个信息窗口。我可以在地图上看到标记,但是当我单击标记以获取 InfoWindow 时,我收到此错误TypeError: Cannot read property 'isOpen' of undefinedthis.setState({isOpen: !this.state.isOpen})onToggleOpen.

代表感谢

componentWillMount() {
    this.setState({ markers: [], isOpen: false })
  }

componentDidMount() {
    let list = { restaurants : []}
    database.ref('..').on('value', .. => {
            ...
            })
            this.setState({ markers:  list.restaurants});
        })

}

onToggleOpen(){
    this.setState({isOpen: !this.state.isOpen})
}


render() { 
    const MapWithAMarker = compose(
    withProps({
        googleMapURL: ...,
        loadingElement: ...,
        containerElement: ...,
        mapElement: ...
      }),
      withScriptjs,
      withGoogleMap
    )(props =>
      <GoogleMap
        defaultZoom={17}
        defaultCenter={{ lat: ..., lng: ... }}
      >
          {props.markers.map(marker => (
            <Marker
              key={marker.name}
              position={{ lat: marker.latitude, lng: marker.longitude }}
              onClick={this.onToggleOpen}
            >
            {this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}> marker.key </InfoWindow>}
            </Marker>
          ))}


      </GoogleMap>
    );
    return (
        <section id="mapa">
            <div class= "container">
                <div class="row">
                    <div class="col-md-12 text-left">
                        <h2 class="section-heading">MAPA</h2>

                        <MapWithAMarker markers={this.state.markers}/>

                    </div>
                </div>
                <div class="row text-center">

                </div>
            </div>
        </section>
    ) 
}

编辑:更新代码:

export default class Mapa extends Component {
  constructor(props) {
    super(props)
    this.state = {
      markers: [],
      isOpen: false
    }
  }

componentDidMount() {
    let list = { restaurants : []}
    database.ref('..').on('value', restaurants => {
            restaurants.forEach( restaurant => {
                    list.restaurants.push({'name': restaurant.key,
                            'longitude': restaurant.val().lng,
                            'latitude': restaurant.val().lat}

                        )
            })
            this.setState({ markers:  list.restaurants });
        })

}

onToggleOpen = () => {
        this.setState({isOpen: !this.state.isOpen})
    }

render() { 

    const MapWithAMarker = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=...&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />
      }),
      withScriptjs,
      withGoogleMap
    )(props =>
      <GoogleMap
        defaultZoom={17}
        defaultCenter={{ lat: .., lng: ... }}
      >
          {props.markers.map(marker => (
            <Marker
              key={marker.name}
              position={{ lat: marker.latitude, lng: marker.longitude }}
              onClick={this.onToggleOpen}
            >
            {this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}> marker.key </InfoWindow>}
            </Marker>
          ))}

      </GoogleMap>
    );
    return (
        <section id="mapa">
            <div class= "container">
            <h3 class="info-title"><span class="info-title-span">Tasty and Convenient.</span></h3>
                <div class="row">
                    <div class="col-md-12 text-left">


                        <MapWithAMarker markers={this.state.markers}/>

                    </div>
                </div>
                <div class="row text-center">

                </div>
            </div>
        </section>
    ) 
}
4

2 回答 2

5

该错误表明this.state == undefined在您尝试检索的范围内this.state.isOpen

这是因为您的this.onToggleOpen()函数范围未正确绑定到您的组件。

尝试重构它以使用如下箭头函数:

onToggleOpen = () => {
    this.setState({isOpen: !this.state.isOpen})
}

边注:

声明 initial 的最佳实践this.state是在组件的constructor生命周期方法中这样做,如下所示:

constructor(props) {
  super(props)
  this.state = {
    markers: [],
    isOpen: false
  }
}

此外,应该this.state.isOpen是您每个人的独特属性,markers而不是所有人的总括价值?这样您就可以单独打开每个标记,而不是一次打开所有标记。

示例解决方案:

// Dependencies.
import React from 'react'
// GoogleMap, etc ..

// Map.
export default class Map extends React.Component {

  // State.
  state = {markers: []}

  // Render.
  render() {

    // Map With A Marker.
    const MapWithAMarker = compose(
      withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=...&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{height: `100%`}}/>,
        containerElement: <div style={{height: `400px`}}/>,
        mapElement: <div style={{height: `100%`}}/>
      }),
      withScriptjs,
      withGoogleMap
    )(props =>
      <GoogleMap defaultZoom={props.zoom} defaultCenter={{lat: props.lat, lng: props.lng}}>
        {props.markers.map(props => <RestaurantMarker key={props.name} {...props}/>)}
      </GoogleMap>
    )

    // Return Map.
    return (
      <section id="map">
        <div class= "container">
        <h3 class="info-title"><span class="info-title-span">Tasty and Convenient.</span></h3>
          <div class="row">
            <div class="col-md-12 text-left">
              <MapWithAMarker 
                markers={this.state.markers}
                lat={37.7749}
                lng={122.4194}
                zoom={17}
              />
            </div>
          </div>
          <div class="row text-center">
            Text
          </div>
        </div>
      </section>
    )

  }

  // Did Mount.
  componentDidMount() {

    // Download Restaurants.
    database.ref('..').on('value', restaurants => {

      // Restaurants Placeholder.
      let markers = []

      // Map Restaurants To List.
      restaurants.forEach(restaurant => {
        markers.push({
          'name': restaurant.key,
          'longitude': restaurant.val().lng,
          'latitude': restaurant.val().lat
        })
      })

      // Update State.
      this.setState({markers})

    })

  }

}


// RestaurantMarker.
class RestaurantMarker extends React.Component {

  // State.
  state = {open: false}

  // Render.
  render() {

    // Extract Props.
    const {name, latitude, longitude} = this.props

    // Return Restaurant Marker Component.
    return (
      <Marker key={name} position={{ lat: latitude, lng: longitude }}>
        {this.state.open && (
          <InfoWindow onClick={() => this.setState(state => ({open: !state.open}))}> {name} </InfoWindow>
        )}
      </Marker>
    )

  }

}
于 2017-10-20T22:18:39.163 回答
0

我在主包装器中做了这个

withStateHandlers(() => ({
    isOpen: {},
  }), {
    onToggleOpen: ({ isOpen }) => (id) => ({
      isOpen: {
        ...isOpen,
        [id]:isOpen[id]==undefined?true:!isOpen[id]
      },
    })
  }),

这在标记组件上

{props.servicePoints.map((x) =>
        <Marker
          onClick={()=>{
            props.onToggleOpen(x.id);
          }}
          animation={google.maps.Animation.DROP}
          key={x.id}
          icon={"favicon.ico"}
          position={{ lat: x.latitude, lng: x.longitude }}
        >
          {props.isOpen[x.id]===true &&
            <InfoWindow
              key={x.id}
              options={{ closeBoxURL: ``, enableEventPropagation: true }}
              onCloseClick={()=>{
                props.onToggleOpen(x.id);
              }}>
              <div>
                <label>Nome:{x.name}</label><br></br>
                <label>Descrizione:{x.description}</label><br></br>
                <label>Indirizzo:{x.address}</label>
              </div>
            </InfoWindow>}}
         </Marker>
      )}

一切正常。因此,如果我单击一个标记,则只会出现一个信息窗口。

于 2020-03-20T17:47:00.767 回答