react google maps ReferenceError:未定义状态



我正在构建一个带有可点击标记和信息窗口的谷歌地图。我得到了这个错误,"ReferenceError:状态未定义",我不知道是什么原因导致的

这是我的组件函数:

export class Container extends React.Component {
render() {
if (!this.props.loaded) {
return <div>Loading...</div>;
}
const style = {
width: "100vw",
height: "90vh"
};
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {}
};
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
onMapClicked = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};
return (
<div style={style}>
<Map
item
xs={12}
google={this.props.google}
onClick={this.onMapClick}
zoom={13}
initialCenter={{ lat: 39.3643, lng: -74.4229 }}
>
<Marker
onClick={this.onMarkerClick}
title={"The marker`s title will appear as a tooltip."}
name={"Salvation Army"}
position={{ lat: 39.3549, lng: -74.4429 }}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
>
<div>
<h1>{this.state.selectedPlace.name}</h1>
</div>
</InfoWindow>
</Map>
</div>
);
}
}

一切似乎都是对的,但我仍然收到错误。如有任何帮助,我们将不胜感激!

您在渲染方法中使用state变量,而不首先声明它。

const state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {}
};

您很可能打算将其改为类属性。

const style = {
width: "100vw",
height: "90vh"
};
export class Container extends React.Component {
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {}
};
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
onMapClicked = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};
render() {
if (!this.props.loaded) {
return <div>Loading...</div>;
}
return (
<div style={style}>
<Map
item
xs={12}
google={this.props.google}
onClick={this.onMapClick}
zoom={13}
initialCenter={{ lat: 39.3643, lng: -74.4229 }}
>
<Marker
onClick={this.onMarkerClick}
title={"The marker`s title will appear as a tooltip."}
name={"Salvation Army"}
position={{ lat: 39.3549, lng: -74.4429 }}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
>
<div>
<h1>{this.state.selectedPlace.name}</h1>
</div>
</InfoWindow>
</Map>
</div>
);
}
}

相关内容

  • 没有找到相关文章