Я недавно протестировал свое собственное приложение реагировать на IOS и увидел странную ошибку: один из моих вызовов setState не обновляет мое состояние, и я проверил, все ли было правильно.
Я работаю над приложением по продаже недвижимости. Этот setState предназначался для того, чтобы на карте, когда пользователь щелкает маркер, отображалось поле состояния, по которому щелкнули подробные сведения. Поэтому, когда пользователь щелкает, он получает индекс состояния, по которому щелкнули, и заполняет им состояние var currentEstate.
Кроме того, он появляется только на IO, на Android все работает нормально, есть идеи?
Вот код:
Моя функция переключения недвижимости, которая содержит setState
_toggleEstate(index, coords) {
// This is what i want to put in my currentEstate, and it's not empty
console.log(this.state.estates[index]);
this.setState(
{
currentEstate: this.state.estates[index]
},
function() {
// But this is empty, so the setState didn't work
console.log(this.state.currentEstate);
}
);
var newRegion = {
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.00522,
longitudeDelta: 0.0221
};
this.mapRef.animateToRegion(newRegion, 500);
}
Моя функция renderEstate, которая проверяет, является ли currentEstate пустым, и возвращает компонент JSX, если нет:
_renderEstateItem() {
if (this._isEmpty(this.state.currentEstate)) {
return null;
} else {
return (
<View style={styles.estateContainer}>
<EstateItem
estate={this.state.currentEstate}
displayDetailForEstate={this._displayDetailForEstate}
showImage={false}
/>
</View>
);
}
}
И мой компонент JSX:
render() {
return (
<View style={styles.mainContainer}>
<MapView
initialRegion={{
latitude: 48.8691526048,
longitude: 2.352065575453187,
latitudeDelta: 0.1922,
longitudeDelta: 0.0421
}}
ref={ref => {
this.mapRef = ref;
}}
onPress={() => this._clickOnMap()}
style={{ flex: 1 }}
>
{this.state.markers.map((marker, index) => {
const coords = {
latitude: marker.lat,
longitude: marker.lng
};
return (
<MapView.Marker
key={index}
coordinate={coords}
title={this.state.estates[index].adress}
description={
numeral(this.state.estates[index].price)
.format("0,0")
.replace(",", " ") + "€"
}
pinColor={color.electricViolet}
onPress={() => this._toggleEstate(index, coords)}
/>
);
})}
</MapView>
<TouchableOpacity
onPress={() => this._goToList()}
style={
this._isEmpty(this.state.currentEstate)
? styles.listButton
: styles.listButtonUp
}
>
<Image
style={styles.listIcon}
resizeMode="contain"
source={require("../assets/images/purple_icons/List.png")}
/>
</TouchableOpacity>
// Here it is when it's suppose to render
{this._renderEstateItem()}
{this._displayLoading()}
</View>
);
}
И, наконец, конструктор:
constructor(props) {
super(props);
this.mapRef = null;
this.myResearch = this.props.navigation.state.params.myResearch;
this.state = {
isLoading: false,
estates: [],
markers: [],
currentEstate: []
};
Geocoder.init(constants.GOOGLE_MAPS_API);
this._displayDetailForEstate = this._displayDetailForEstate.bind(this);
}
Заранее спасибо!