2016-12-24 1 views
0

를 설정할 수 없습니다, 기본 + 타이프 라이터 반응 탐지 및 작동하지 않는 것 같습니다.내가 내 기능이 실행되고 있지만 어떤 이유에서 내가 로그인을 기반으로 setState를)합니다 (componentDidMount에서이 속성 "isLoggedIn"</p> <p>의 상태를 설정할 수 없습니다 알고 주를

import React, { 
    Component 
} from 'react'; 
import { AppRegistry, View, StyleSheet, Text } from 'react-native'; 
import { Actions } from 'react-native-router-flux'; 

import Firestack from 'react-native-firestack'; 

const firestack = new Firestack(); 

interface Props { 
    isLoggedIn?: boolean; 
} 

interface State { 
    isLoggedIn: boolean; 
} 


export default class MainList extends Component<Props, State> { 

    state = { 
     isLoggedIn: false, 
    }; 

    constructor(props: any) { 

     super(props); 
     console.log("Is anyone logged in?: " + this.isLoggedIn); 

    } 

    isLoggedIn = this.state.isLoggedIn; 

    componentDidMount() { 

     firestack.auth.listenForAuth((evt: any) => { 
     // evt is the authentication event 
     // it contains an `error` key for carrying the 
     // error message in case of an error 
     // and a `user` key upon successful authentication 

     if (!evt.authenticated) { 
     // There was an error or there is no user 
     //console.error(evt.error); 

     this.setState({isLoggedIn: false}); 
     console.log("The state of isLoggedIn is: " + this.isLoggedIn); 

     } else { 
     // evt.user contains the user details 
     console.log('User details', evt.user); 

     this.setState({isLoggedIn: true}); 
     console.log("The state of isLoggedIn is: " + this.isLoggedIn); 

     } 

     if (!this.isLoggedIn) { 

      Actions.welcome(); 

     } 


    }); 

} 

render() { 

    return (
     <View style={styles.View}> 

      <Text style={styles.textLabel}>The main view</Text> 

     </View> 
     ) 

    } 

    } 

const styles = StyleSheet.create({ 

    View: { 
     padding: 20 
    }, 
    textLabel: { 
    fontSize: 20, 
    marginBottom: 10, 
    height: 20 
    }, 
textInput: { 
    height: 20, 
    fontSize: 15, 
    marginBottom: 20 
} 

}); 

AppRegistry.registerComponent('MainList',()=> MainList); 

내가 잘못하고있는 것은 무엇입니까?

+0

: 상태를 설정하는이 방법을 사용,

this.setState({ isLoggedIn: false },() => console.log(this.state.isLoggedIn)); 

을 또는 : 즉시 새 값을 액세스 할 경우 상태가 설정 될 때 트리거 콜백을 사용 componentDidMount() – Codesingh

답변

1

이 코드는 작동하지 않습니다. setState은 비동기식이므로 setState을 호출 한 직후에 this.isLoggedIn이 반드시 업데이트되지는 않습니다. 당신이 내부 상태를 설정할 수 없습니다

this.setState(oldState => { 
    oldState.isLoggedIn = false; 

    console.log(oldState.isLoggedIn); 
    return oldState; 
}); 
+1

감사합니다. 비동기라고 생각하지 않았습니다. 거기에 대해 잘 알고 있습니다. 이제 내 문제가 고쳐졌습니다 :-) 감사합니다! –

0

componentDidMount에 데이터를 가져옵니다. 응답이 도착하면 콜백 내에서 setstate를 호출하여 데이터를 상태로 저장합니다.

componentDidMount()는 구성 요소가 마운트 된 직후에 호출됩니다. DOM 노드가 필요한 초기화는 여기에 있어야합니다. 원격 종점에서 데이터를로드해야하는 경우 네트워크 요청을 인스턴스화하는 데 좋습니다. 이 메소드의 상태를 설정하면 (자), 재 렌더링이 실행됩니다.