我正在构建水提醒应用程序,并且每天将消耗的水量存储在应用程序状态和AsyncStorage中。
我想在每天结束时自动将其设置为零。
如下所示。我以醉状态存储消耗的水量,并通过将目标划分为醉来计算进度。
我正在从AsyncStorage获取目标并将其设置为状态。
Walkable
答案 0 :(得分:1)
基本上,您想要执行遵循此模式的操作。
检查存储的日期,并将其与当前日期进行比较。如果没有存储日期,请存储日期。否则,如果当前日期大于存储的日期,请重置这些值。
当应用程序从后台运行到前台时,甚至返回主屏幕时,请检查存储的日期并将其与当前日期进行比较。如果当前日期大于存储的日期,请重置这些值。
在处理时间时,moment
是一个很好的软件包。经过充分测试。您可以在https://momentjs.com上找到有关它的更多信息。您可以使用npm i moment
代码如下:
import React from 'react';
import { View, StyleSheet, AsyncStorage, AppState } from 'react-native';
import moment from 'moment';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
appState: AppState.currentState, // set the currentState as the appState
}
}
async componentDidMount () {
// Set the listener
AppState.addEventListener('change', this._handleAppStateChange);
// perform check when the component mounts
await this.checkDate();
}
componentWillUnmount () {
// remove the listener
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = async (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
// app has come to the foreground
// perform checks etc here
await this.checkDate();
}
// update the appState
this.setState({ appState: nextAppState });
}
checkDate = async () => {
// create a string with the current date
let currentDateString = moment('YYYY-MM-DD')
// get the value from storage
let savedDateString = await AsyncStorage.getItem('storedDate');
if (savedDateString) {
if (moment(currentDateString).isAfter(savedDateString)) {
// this is where you put the code that resets everything
// clear the values that you have previously saved
// remember to save the new date
try {
await AsyncStorage.setItem('storedDate', currentDateString)
} catch (err) {
}
} else {
// don't do anything as the time hasn't changed
// so we could really get rid of this else statement
}
} else {
// save the time as this is the first time the app has launched
// do any other initial setup here
try {
await AsyncStorage.setItem('storedDate', currentDateString)
} catch (err) {
}
}
}
render() {
return (
<View style={styles.container}>
</View>
)
}
}
代码应使您了解如何实现它。