如何在 React Native 中初始化 AsyncStorage 变量?

How to initialize AsyncStorage variable in React Native?

我试过按照这个 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>
    );
  }
}

在您的 componentDidMount 中,您应该在设置状态之前检查虚假值:

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

我建议对您的代码使用 flow-type 或等效的类型检查器,以更轻松地找到此类错误。