【问题标题】:componentDidUpdate update logged just after click in screen在屏幕中单击后立即记录 componentDidUpdate 更新
【发布时间】:2019-10-02 00:25:04
【问题描述】:

我正在构建一个 React Native 应用程序,但我在 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);
      }
  })

};

【问题讨论】:

    标签: javascript firebase react-native redux


    【解决方案1】:

    就个人而言,我会丢失 componentDidMount 和 componentDidUpdate 的逻辑,只需将 onAuthStateChange 放在 componentDidMount 中,这样您就可以执行导航到页面。

    无论如何,您的问题是 componentDidUpdate 在页面刷新时执行,并且在您与之交互之前不会发生,这就是为什么它只在您触摸屏幕后分析记录的变量。如果您认为每次收到新道具时都会执行 componentDidUpdate,那是错误的。

    你应该检查这个https://es.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

    【讨论】:

    • 感谢您的回答。但是如果每次我的 props 更改时 componentDidUpdate 都没有更新(使用 redux),我该如何处理这个操作,并且只有在我从 props 调用的操作中得到响应时才渲染我的组件?
    • 嗯,首先,我看不到你的 onAuthStateChange 中的代码,因为那是异步的,你实际上可能甚至没有调用 redux。第二个 componentDidUpdate 可能会在 UI 更改时触发。
    • 我更新了我的代码,我可以理解这不起作用的原因,因为我正在更新我的状态......
    • 我认为您的代码中发生的事情是 DOM 实际上并未使用您记录的道具进行修改,因此渲染不会触发,因此 componentDidUpdate 不会触发。尝试使用 dom 中的记录变量,如隐藏变量或文本,看看是否有效。不过,我通常反对这种类型的流程。我会在相同的逻辑中使用 onAuth 并从中导航,而不是从 redux 中的道具更新中导航。 (即使您想在同一步骤中更新会话)
    • 经过一番头疼后,我发现问题出在我的调试上。我禁用它并工作。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多