2017-11-08 31 views
0

私はこれを試してみましたtutorial。最初はスコアを表示しません。私がしたいことは、30という初期スコアがあるということです。ユーザーがボタンを押すと、そのボタンで20が差し引かれます。だから、ユーザーがアプリを再ロードするとき、それはあなたのcomponentDidMount 10.React NativeでAsyncStorage変数を初期化する方法は?

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> 
    ); 
    } 
} 

答えて

1

のスコアが表示されます、あなたは状態を設定する前にfalsy値をチェックする必要があります

componentDidMount =() => 
    AsyncStorage.getItem('points').then((value) => { 
    if (value) { 
     this.setState({ 'points': value }) 
    } 
    }) 

を私はflow-typeまたは同等の使用をお勧めしますこのようなバグをより簡単に見つけるためにコードのチェッカーをタイプしてください。

関連する問題