如何在异步存储中存储按钮按下的次数



当我按下按钮时,这个数字会增加 1。

但是,刷新屏幕后,数字显示"0"。

我想在刷新之前显示它停止的数字。

我应该在哪里修复以正确存储在AsyncStorege中的值?你能给一些建议吗?

export default class ApplauseButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      applause: 0,
    };
  }
  componentDidMount = () => {
    const applauseCount = parseInt(AsyncStorage.getItem('applause'),10);
      this.setState({applaused:applauseCount});
  };
  handlClick() {
    const countapplause = this.state.applause + 1;
     AsyncStorage.setItem('applause', countapplause.toString()).then(() => {
       this.setState({ applause: this.state.applause + 1});
     });
   };
  render() {
    return (
      <View style={styles.container}>
        <Button title="👋"
          onPress={() => {
            this.handlClick()
          }} />
        <Text style={styles.count}>
          {this.state.applause}/
        </Text>
      </View>
    );
  }
}
我想

你应该改变两件事:

1.设置从异步存储获取计数时的状态。

2.您在异步存储中设置以前的值,而是存储递增的值。

componentDidMount = () => {
  getcount();
};
 getcount = async () => {
  let count = '';
  try {
    count = await AsyncStorage.getItem('applause') || '0';
     count = parseInt(count,10);
     this.setState({applause:count})
  } catch (error) {
    // Error retrieving data
    console.log(error.message);
  }
}

handlClick= async ()=> {
         const count = this.state.applause + 1;
        try{
        await AsyncStorage.setItem('applause', count.toString());
           this.setState({ applause: count});
       }
       catch(error){
        console.log(error.message);
       }
    };

最新更新