在加载应用程序时,状态未通过AsyncStorage更新

问题描述 投票:1回答:1

我正在尝试建立一个水提醒应用程序。我有3个屏幕,我正在使用react-navigation

  • 家(我允许用户当天增加饮酒量并显示他们喝多少水)
  • 通知(如果用户希望接收通知和何时接收,则使用切换按钮定义的用户)
  • 设置(用户输入年龄,体重以确定他们应该每天饮用多少)。这是用户下载应用时看到的第一个屏幕

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

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>
 )
}
javascript react-native asyncstorage
1个回答
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();
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.