【发布时间】:2019-10-05 12:54:18
【问题描述】:
我最近在 IOS 上测试了我的 react native 应用程序,发现了一个奇怪的错误:我的一个 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);
}
提前致谢!
【问题讨论】:
-
请告诉我你的构造函数。
-
好的,检查我的答案并标记答案并 +1,如果有效。
-
检查我更新的答案。
-
不幸的是还是一样...坐标仅用于放大我的地图,它没有什么可处理的。即使我这样做 'this.setState({currentEstate: "hello"})' 它也不起作用
-
建议 - 删除组件中的所有杂物,直到您可以进行简单的 setState 调用。完成后,开始慢慢添加东西,直到它再次中断。这样做你会发现哪里出了问题。
标签: javascript ios reactjs react-native jsx