gpt4 book ai didi

javascript - 关闭应用程序后 React Native 进度条百分比不保持不变

转载 作者:行者123 更新时间:2023-11-28 07:06:01 25 4
gpt4 key购买 nike

每次我按下按钮时,进度条都会上升 %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);

最佳答案

问题是您正在获取 PROGRESS 的旧值(在增加 0.2 之前)并将该值设置为项目 progressbar

因此,每次重新加载时,React 都会运行 componentDidMount 函数,并且由于您将 progressbar 设置为 PROGRESS 的旧值,因此它始终会显示落后一个增量您在 View 中看到的内容。

尝试将 onButtonPress() 更改为:

onButtonPress() {
PROGRESS += 0.2;
AsyncStorage.setItem('progressbar', JSON.stringify(PROGRESS))
... // continues normally

关于javascript - 关闭应用程序后 React Native 进度条百分比不保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com