我已经尝试了本教程。它一开始不会显示任何分数。我想做的是初始分数为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>
);
}
}
在componentDidMount
中,您应该在设置状态之前检查 faly 值:
componentDidMount = () =>
AsyncStorage.getItem('points').then((value) => {
if (value) {
this.setState({ 'points': value })
}
})
我建议为您的代码使用 flow-type
或等效的类型检查器,以便更轻松地查找此类错误。