我有一个应用程序,如果你点击地图就可以放置一个标记。但是,无论何时单击它,它都是第一次返回未定义。之后,它没有放置标记。为什么是这样?我是否对州管理做错了什么?
constructor(props) {
super(props);
this.state = {
coordinate : {
latitude: undefined,
longitude: undefined
}
}
this.handleMarkerPress = this.handleMarkerPress.bind(this);
}
handleMarkerPress = (event) => {
this.setState({
coordinate: {
lat: this.event.nativeEvent.coordinate.latitude,
long: this.event.nativeEvent.coordinate.longitude
}
})
console.log(this.state);
}
markerIsNull() {
if (this.state.coordinate.longitude == null) {
return null;
}
else {
return <MapView.Marker coordinate={this.state.coordinate} />;
}
}
render() {
return (
<View style={styles.container}>
<MapView
style = {
{
flex: 1
}
}
initialRegion = {
{
latitude: 42.974536,
longitude: -82.406590,
latitudeDelta: 0.00003,
longitudeDelta: 0.00002,
}
}
onPress={(event) => this.handleMarkerPress(event)}
>
{ this.markerIsNull() }
</MapView>
</View>
);
}
答案 0 :(得分:1)
您将initialState
设为
coordinate : {
latitude: undefined,
longitude: undefined
}
并将其更新为
coordinate: {
lat: this.event.nativeEvent.coordinate.latitude,
long: this.event.nativeEvent.coordinate.longitude
}
并根据initialState
键进行检查,因此始终为undefined
您可以将其直接设为coordinate: event.nativeEvent.coordinate