【问题标题】:Having trouble trying to implement AsyncStorage in React Native尝试在 React Native 中实现 AsyncStorage 时遇到问题
【发布时间】:2026-02-02 05:05:01
【问题描述】:

我正在使用 react native 来构建应用程序,我遇到的唯一问题是我有一个进度条来跟踪用户的进度,但是当我完全关闭应用程序并重新打开它时,一切都会重置为原始状态数据。所以我求助于 AsyncStorage 来保存我的数据,但我在试图弄清楚如何在我的代码中使用它时遇到了麻烦,如果有人能提供帮助,那就太好了。

*更新: 我尝试实现异步存储,当我完全关闭应用程序时数据似乎一直存在,但我有它,所以每次按下按钮时进度条都会上升 %20,例如,如果它在 %80 并且我重新加载应用程序它将显示为 %60,我想知道是否有人可以帮助我解决此问题,以在重新加载或关闭应用程序后使进度条百分比保持不变。

'use strict';

var React = require('react-native');
var ProgressBar = require('react-native-progress-bar');

var {
  AppRegistry,
  AsyncStorage,
  StyleSheet,
  Text,
  View,
  TouchableHighlight
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFF',
  },
  button: {
    alignSelf: 'center',
    marginTop: 50,
    width: 100,
    height: 50,
    backgroundColor: '#0059FF',
    borderRadius: 8,
    borderWidth: 2,
    borderColor: '#0059FF'
  },
  buttonClear: {
    alignSelf: 'center',
    marginTop: 10,
    width: 100,
    height: 50,
    backgroundColor: '#3B3A3A',
    borderRadius: 8,
    borderWidth: 2,
    borderColor: '#3B3A3A'
  },
  buttonText: {
    fontSize: 18,
    textAlign: 'center',
    lineHeight: 33,
    color: '#FFF',
  }
});

var PROGRESS = 0;

class BasicStorageExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      progress: PROGRESS
    }
  }

  componentDidMount() {
    AsyncStorage.getItem('progressbar')
      .then((value) => {
        JSON.parse(value);
        this.setState({
          progress: value 
        });
        console.log('Progress on load: ' + value);
      })
      .done();
  }

  onButtonPress() {
    AsyncStorage.setItem('progressbar', JSON.stringify(PROGRESS))
      .then(() => {
        JSON.parse(PROGRESS);
        this.setState({
          progress: PROGRESS += 0.2
        });
        console.log('Progress on Button Press: ' + PROGRESS);
      })
      .done();
  }

  onButtonClearPress() {
    AsyncStorage.setItem('progressbar', JSON.stringify(PROGRESS))
      .then(() => {
        JSON.parse(PROGRESS);
        PROGRESS = 0;
        this.setState({
          progress: 0
        });
      })
      .done();
  }

  render() {
    return (
      <View style={styles.container}>
        <ProgressBar
          fillStyle={{}}
          backgroundStyle={{backgroundColor: '#cccccc', borderRadius: 2}}
          style={{marginTop: 10, width: 300}}
          progress={this.state.progress} />
        <TouchableHighlight
          ref="button"
          style={styles.button}
          underlayColor='#002C7F'
          onPress={this.onButtonPress.bind(this)}>
          <Text style={styles.buttonText}>Done</Text>
        </TouchableHighlight>
        <TouchableHighlight
          style={styles.buttonClear}
          underlayColor='#002C7F'
          onPress={this.onButtonClearPress.bind(this)}>
          <Text style={styles.buttonText}>Clear</Text>
        </TouchableHighlight>
      </View>
    );
  }
};

AppRegistry.registerComponent('BasicStorageExample', () => BasicStorageExample);

【问题讨论】:

    标签: javascript ios react-native


    【解决方案1】:

    只需调用AsyncStorage.setItem('some-id', someVar) 进行设置,然后调用AsyncStorage.getItem('some-id') 进行检索。它类似于本地存储。文档中有完整的 API 和示例:

    https://facebook.github.io/react-native/docs/asyncstorage.html

    【讨论】:

    • 谢谢,我查看了 API,发现只能使用 AsyncStorage 存储字符串,你知道如何存储数字吗?
    • 只需将 JSON 存储在其中。在 JS 中创建一个对象,然后将其序列化: JSON.stringify({ myNum: 5 }) - 这将为您提供一个可以存储的字符串,然后使用 JSON.parse 将其转回一个对象。
    • 如果有帮助,我创建了一个名为 react-native-simple-store 的超级简单模块,它包装了 AsycnStorage 并为您处理 JSON 字符串化和解析。
    • 为什么他们在文档中使用长且最高机密的密钥名称?这是有原因的吗?
    【解决方案2】:

    用于存储数据

    AsyncStorage.setItem('progressbar', JSON.stringify(PROGRESS))
    

    用于异步获取数据调用。

    async componentWillMount() {
        const result = await AsyncStorage.getItem('progressbar');
    
        // you will get value. check your conditions here
    }
    

    【讨论】: