我需要为地图中的每个标记创建一个信息窗口。我可以在地图上看到标记,但是当我点击标记以获取InfoWindow时,我收到此错误TypeError: Cannot read property 'isOpen' of undefined
,引用this.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>
)
}
答案 0 :(得分:5)
该错误表示您尝试检索this.state == undefined
的范围内的this.state.isOpen
。
这是因为您的this.onToggleOpen()
功能范围未正确绑定到您的组件。
尝试重构它以使用箭头函数,如下所示:
onToggleOpen = () => {
this.setState({isOpen: !this.state.isOpen})
}
旁注:
声明初始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>
)
}
}
的唯一属性吗?这样您就可以单独打开每个标记,而不是一次打开所有标记。
示例解决方案:
char *string = malloc(50);
答案 1 :(得分:0)
我是在主包装中完成的
withStateHandlers(() => ({
isOpen: {},
}), {
onToggleOpen: ({ isOpen }) => (id) => ({
isOpen: {
...isOpen,
[id]:isOpen[id]==undefined?true:!isOpen[id]
},
})
}),
这在Marker组件上
{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>
)}
一切正常。因此,如果我单击一个标记,则只会显示一个InfoWindow。