加载应用后,状态不会通过AsyncStorage更新

时间:2019-03-23 13:02:59

标签: javascript react-native asyncstorage

我正在尝试构建水提醒应用程序。我有3个屏幕,正在使用反应导航

  • 家庭(我允许用户当天增加饮酒量并显示他们喝了多少水
  • 通知(用户可以根据需要定义开关按钮 接收通知以及何时接收)
  • 设置(用户输入年龄,体重来确定他们的体重) 应该每天喝)。这是用户首次看到的屏幕 下载了应用程序

我每天使用检查日期功能将醉酒值设为零。我的问题是,加载应用程序后,醉酒值不会自动设置为零。其余值(例如进度)将设置为零,但不会设置为醉酒值。当我更改一个屏幕并返回主屏幕时,它设置为零。

state = {
    progress: 0,
    drunk: 0,
    open: false,
    goal: 0,
};

componentDidMount() {
    this.willFocusSubscription = this.props.navigation.addListener('willFocus', payload => {
        // perform check when the component mounts
        this.checkDate();

        // retrieve data from AsyncStorage
        this._retrieveData();
    });
}

// function to retreive data from AsyncStorage
_retrieveData = async () => {
    try {
        const sliderValue = await AsyncStorage.getItem('sliderValue');
        const drunk = await AsyncStorage.getItem('drunk');
        const progress = await AsyncStorage.getItem('progress');

        if (sliderValue !== null) {
            // We have data!! ve stateleri belirledik
            this.setState({ goal: parseInt(sliderValue) });
        } else if (sliderValue === null) {
            this.setState({ goal: 0 });
        }

        if (drunk !== null) {
            this.setState({ drunk: parseInt(drunk) });
        } else if (drunk === null) {
            this.setState({ drunk: 0 });
        }

        if (progress !== null) {
            this.setState({ progress: parseFloat(progress) });
        } else if (progress === null) {
            this.setState({ progress: 0 });
        }

    } catch (error) {
        console.log(error.message);
    }
};

// function to check date and set drunk to zero
checkDate = async () => {
    // create a string with the current date
    let currentDateString = moment().format('DDMMYYYY');

    // get the value from storage
    let savedDateString = await AsyncStorage.getItem('storedDate');

    // create variables for differences on year month
    let yearDiff = currentDateString.slice(4) - savedDateString.slice(4)
    let monthDiff = currentDateString.slice(2, 4) - savedDateString.slice(2, 4)
    let dayDiff = currentDateString.slice(0, 2) - savedDateString.slice(0, 2)

    // if there is a value on AsyncStorage
    if (savedDateString) {
        // if difference is bigger than zero set drunk and progress to zero
        if (yearDiff > 0 || monthDiff > 0 || dayDiff > 0) {
            // this is where you put the code that resets everything
            // clear the values that you have previously saved
            // remember to save the new date
            this.setState({ drunk: 0, progress: 0 }, () => {
                this._storeData();
            });
            try {
                await AsyncStorage.setItem('storedDate', currentDateString);
            } catch (err) {
                console.debug(err.message);
            }
        }
    } 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) {
            console.debug(err.message);
        }
    }
};

render() {
    return (
        <Provider>
            <View style={styles.container}>
                <Text style={styles.drunk}>
                    {this.state.drunk.toFixed(0)} / <Text style={styles.goal}>{this.state.goal}</Text>
                </Text>
            </View>
        </Provider>
 )
}

1 个答案:

答案 0 :(得分:0)

我遇到的问题是我在导航侦听器中调用AsyncStorage方法。由于AsyncStorage是异步工作的,因此AsyncStorage方法不会在导航侦听器中完成。

我如何解决此问题的方法是,我使componentDidMount异步函数并使用await调用导航侦听器之外的方法。

async componentDidMount() {
    // perform check when the component mounts
    await this.checkDate();

    // retrieve data from AsyncStorage
    await this._retrieveData();

    this.willFocusSubscription = this.props.navigation.addListener('willFocus', payload => {
        // perform check when the component mounts
        this.checkDate();

        // retrieve data from AsyncStorage
        this._retrieveData();
    });
}