【发布时间】: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