AsyncStorage работает только при перезагрузке приложения - PullRequest
0 голосов
/ 10 июля 2020

я установил свои значения в Asyn c хранилище при входе в систему

fetch('http://xxxxx/xxxx/getUserDetails.php', {
                            method: 'POST',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                user_id: this.state.userEmail,
                            })
                        })
                            .then((response) => response.json())
                            .then((responseJson) => {
                                const name = responseJson[0]['name'];
                                const profilePicture = responseJson[0]['profile_picture'];
                                const userId = responseJson[0]['id'];
                                const loginMode = responseJson[0]['login_mode'];
                                AsyncStorage.setItem('active', 'true');
                                AsyncStorage.setItem('userEmail', this.state.userEmail);
                                AsyncStorage.setItem('name', name);
                                AsyncStorage.setItem('profilePicture', profilePicture);
                                AsyncStorage.setItem('userID', userId);
                                AsyncStorage.setItem('loginMode', loginMode)
                                setTimeout(async () => {
                                    this.setState({ isLoading: false })
                                    this.props.navigation.navigate('userScreen');
                                }, 500)
                            })
                            .catch((error) => {
                                console.log(error);
                            })
                    }

и удалил их при выходе из системы. сведения о пользователе отображаются на странице входа. если я перезагружаю свое приложение, отображаются новые значения, хранящиеся в хранилище asyn c, почему это происходит, а этого не происходит?

Я использую здесь AsyncStorage.

async componentDidMount() {
        const userEmail = await AsyncStorage.getItem('userEmail');
        const name = await AsyncStorage.getItem('name');
        const profilePicture = await AsyncStorage.getItem('profilePicture');
        const userID = await AsyncStorage.getItem('userID');
        this.getWish();
        this.getAddFunction();
        this.setState({ userEmail })
        this.getResumeVideo(userEmail);
        this.getDemoVideo();
        this.getClass();
        this.setState({
            userEmail,
            name,
            profilePicture,
            userID
        })
        this.getNotificationCount(userID);
        Orientation.lockToPortrait();
        this._unsubscribe = this.props.navigation.addListener('focus', () => {
            this.getAddFunction();
            this.getDemoVideo();
            this.getResumeVideo(this.state.userEmail);
            this.getClass();
            this.getNotificationCount(userID);
        });
    }

1 Ответ

0 голосов
/ 11 июля 2020

Единственное место, где вы вызываете setState и сообщает response, что он должен назначить новое значение для состояния (и отобразить ...) его в componentDidMount, поэтому React не знает, что он должен отображать снова.

При присвоении нового значения AsyncStorage вы также можете позвонить setState

fetch('http://xxxxx/xxxx/getUserDetails.php', {
                            method: 'POST',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                user_id: this.state.userEmail,
                            })
                        })
                            .then((response) => response.json())
                            .then((responseJson) => {
                                const name = responseJson[0]['name'];
                                const profilePicture = responseJson[0]['profile_picture'];
                                const userId = responseJson[0]['id'];
                                const loginMode = responseJson[0]['login_mode'];
                                AsyncStorage.setItem('active', 'true');
                                AsyncStorage.setItem('userEmail', this.state.userEmail);
                                AsyncStorage.setItem('name', name);
                                AsyncStorage.setItem('profilePicture', profilePicture);
                                AsyncStorage.setItem('userID', userId);
                                AsyncStorage.setItem('loginMode', loginMode)
                                setTimeout(async () => {
                                    this.setState({ isLoading: false })
                                    this.props.navigation.navigate('userScreen');
                                }, 500)

                             // here
                               this.setState({
                                 name,
                                 profilePicture,
                                 userID
                              })
                            })
                            .catch((error) => {
                                console.log(error);
                            })
                    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...