如何在每天结束时自动将状态设置为零



我正在构建水提醒应用程序,并将每日消耗的水量存储在应用程序状态和AsyncStorage中。

我想在每天结束时自动将其设置为零。

正如你在下面看到的。我正在存储醉酒状态下的消耗水量,并通过将目标划分为醉酒来计算进度。

我正在从AsyncStorage获取目标,并将其设置为state。

export default class HomeScreen extends React.Component {
state = {
progress: 0, 
drunk: 0, // this is the state I want to set to zero
goal: 0
};
componentDidMount() {
this.willFocusSubscription = this.props.navigation.addListener(
"willFocus",
payload => {
console.debug("willFocus", payload);
//retrieve items from AsyncStorage
_retrieveData = async key => {
try {
const sliderValue = await AsyncStorage.getItem("sliderValue");
const drunk = await AsyncStorage.getItem("drunk");
const progress = await AsyncStorage.getItem("progress");
if (drunk !== null) {
// We have data!! and set them to states
this.setState({
goal: parseInt(sliderValue),
drunk: parseInt(drunk),
progress: parseFloat(progress)
});
}
} catch (error) {
console.log(error.message);
}
};
_retrieveData();
}
);
}
componentWillUnmount() {
if (this.willFocusSubscription) {
this.willFocusSubscription.remove();
}
}
//function to drink water, set state and setItem Async
drinkWater = () => {
this.setState(prevState => ({
drunk: prevState.drunk + 200,
progress: (prevState.drunk + 200) / this.state.goal
}));
let progress = this.state.progress;
let drunk = this.state.drunk;
_storeData = async () => {
try {
await AsyncStorage.setItem("progress", progress.toString());
await AsyncStorage.setItem("drunk", drunk.toString());
} catch (error) {
console.log(error.message);
}
};
_storeData();
};

基本上,您想做一些遵循此模式的事情。

应用程序启动

检查存储的日期,并将其与当前日期进行比较。如果未存储日期,请存储该日期。否则,如果当前日期大于存储的日期,则重置值。

背景到前景

当应用程序从后台进入前台,甚至返回主屏幕时,请检查存储的日期并将其与当前日期进行比较。如果当前日期大于存储的日期,请重置这些值。

时间

在处理时间问题时,moment是一个很好的使用包。它经过了很好的测试。你可以在这里了解更多信息https://momentjs.com.您可以使用npm i moment进行安装

代码示例

  1. 我们使用AppState来跟踪应用程序是在后台还是在前台。由于应用程序可能在日期更改时运行,我们需要检查它何时出现在前台
  2. 我们需要检查组件何时安装,因为它将在应用程序启动时安装。因此,该应用程序之前可能已经关闭
  3. 在保存日期时忽略时间,因为我们只想比较日期

这是代码:

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>
)
}
}

代码应该让你知道如何实现它

相关内容

  • 没有找到相关文章