我尝试过这个tutorial。它一开始不会显示任何分数。我想要做的是初始得分为30.如果用户按下按钮,则会扣除20。因此,当用户重新加载应用程序时,它应显示10分。
class SupporterMapScreen extends Component<{}> {
...
constructor(props) {
super(props);
this.state = {
isUsed: false,
show: false,
points: 30,
beaconMarkers: {
coordinate: {latitude: 14.554180, longitude: 121.044099},
cost: 20,
},
};
}
componentDidMount = () => AsyncStorage.getItem('points').then((value) => this.setState({ 'points': value }))
createBeacon() {
const { points, beaconMarkers } = this.state;
if(points >= beaconMarkers.cost) {
var totalPoints = points - beaconMarkers.cost;
alert("The beacon has been added!");
this.setState({ isUsed: true, show: true, points: totalPoints });
AsyncStorage.setItem('points', totalPoints);
this.setState({ 'points': totalPoints });
}
else {
...
}
render() {
return (
<View style={styles.container}>
...
<View style = {styles.pointsBar}>
<Text style = {styles.points}>POINTS: {this.state.points}</Text>
</View>
<View style = {styles.beaconPosition}>
<Button
disabled = {this.state.isUsed}
style = {styles.beaconButton}
onPress={ () => Alert.alert(
'Buy Beacon?',
'It costs ' + this.state.beaconMarkers.cost + ' points in order to buy beacon.',
[
{text: 'No'},
{text: 'Yes', onPress: () => this.createBeacon()},
],
{ cancelable: false }
)}
title = 'B'
/>
</View>
</View>
);
}
}
答案 0 :(得分:2)
在componentDidMount
中,您应该在设置状态前检查虚假值:
componentDidMount = () =>
AsyncStorage.getItem('points').then((value) => {
if (value) {
this.setState({ 'points': value })
}
})
我建议您使用flow-type
或等效类型检查器来更轻松地查找此类错误。