Обновление componentDidUpdate регистрируется сразу после нажатия на экране - PullRequest
0 голосов
/ 02 октября 2019

Я создаю собственное приложение, и я столкнулся с проблемой на componentDidUpdate. Когда приложение загружает componentDidMount, вызовите API, чтобы проверить, зарегистрирован ли пользователь (используя firebaseService.auth().onAuthStateChanged), если это так, приложение перенаправляется на главный экран, в противном случае на экран входа в систему. Но компонент просто перенаправляет на один из этих экранов, когда я где-то нажимаю. Кто-нибудь может мне помочь? Спасибо

Следуйте за моим кодом:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, Image, FlatList,ActivityIndicator} from 'react-native';
import logo from '../../asserts/logo.png'
import { TouchableOpacity, TextInput } from 'react-native-gesture-handler';
import ListCard from '../../components/User/ListCard';
import { connect } from 'react-redux';
import axios from 'axios';
import { restoreSession} from '../../store/actions/Section/actions';



class Load extends Component {
    componentDidMount(){
        this.props.restore();
        const { user, logged, error, loading } = this.props;
        console.log("restore");
        if(user && logged) this.props.navigation.navigate('User');
    }

    componentDidUpdate(prevProps) {
        const { user, logged, error,loading } = this.props;
        console.log("aqui");
        if (!loading && !prevProps.error && error) Alert.alert('error', error);
        if (!loading && logged) this.props.navigation.navigate('User');
    }

    constructor() {
      super();
      this.state = {
        animating: false,
        align: 'flex-start',
        alignsecond: false,
      };

      setTimeout(
        () =>
          this.setState({ align: 'flex-start' }, function() {
            this.setState({
              alignsecond: true,
            });
          }),
        100
      );
    }

    render() {
      return (
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            //flexDirection: 'row',
            justifyContent: this.state.align,
            marginTop : 150,
          }}>
          <Image
           source={logo} 
            style={{ width: 200, height: 200 }}
          />
          {!this.state.alignsecond ? null : (
            <View style={{ margin: 10, justifyContent:'center',alignItems:'center' }}>
            <Text
              style={{ color: '#6F1121', fontSize: 30, fontWeight: 'bold' ,justifyContent:'center'}}>
              HomeShare
            </Text>
            <Text
              style={{  fontSize: 15,justifyContent:'center' }}>
              Find a place to Share !
            </Text>
            <ActivityIndicator style={{  marginTop:20 }} size="large" color="gray" />
          </View>
        )}
      </View>
    );
  }

}

const styles = StyleSheet.create({

    containerCard:{
        flex:1,
        flexDirection: 'column',
        paddingTop:10 ,
        paddingLeft:20,
        paddingRight:20,
        backgroundColor: 'rgba(220, 222, 211, 0.25)',


      //  marginTop: (Platform.OS === 'ios') ? 44 : StatusBar.currentHeight, 

    },
    container:{

      flex:1,
      backgroundColor: 'rgba(220, 222, 211, 0.25)',
    }


});


const mapStateToProps = ({ section: { restoring, loading, user, error, logged } }) => ({
    restoring: restoring,
    loading: loading,
    user: user,
    error: error,
    logged: logged
  });

  const mapDispatchToProps = {
        //login:loginUser,
        restore:restoreSession
  };
  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(Load);

Мое действие:

export const restoreSession = () => dispatch => {
  dispatch(sessionLoading());

  firebaseService.auth().onAuthStateChanged(async function(user) {
      if (user) {
        //console.log(user);
        firebaseService.auth().currentUser.getIdToken(true).then(function(idToken) {
         dispatch(sessionSuccess(idToken))


        }).catch(function(error) {
          dispatch(sessionError(e));
        });

        //dispatch(sessionSuccess(user));

      } else {
        dispatch(sessionLogout);
      }
  })

};

1 Ответ

0 голосов
/ 02 октября 2019

Лично я бы потерял логику для componentDidMount и componentDidUpdate и просто поместил здесь onAuthStateChange в componentDidMount, чтобы вы могли выполнить переход на страницу.

В любом случае, ваша проблема в том, что componentDidUpdate выполняется, когда страница обновляется, и этого не произойдет до тех пор, пока вы с ней не будете взаимодействовать, и поэтому он анализирует зарегистрированную переменную только после того, как вы прикоснулись к экрану. Если вы думаете, что componentDidUpdate будет выполняться каждый раз, когда вы получаете новый реквизит, это неправильно.

Вы должны проверить это https://es.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...