2016-12-24 2 views
1

현재 React Native 0.39.2/최신 TypeScript를 사용하고 있으며 componentDidMount() 메소드와 setState를 실행할 때 this.setState가 아닌 다른 오류가 발생합니다. 함수.React Native with TypeScript this.setState가 함수가 아닙니다.

은 내가 유형으로 부울을 사용하고 있기 때문에이 유형의 오류를주고 모든 유형 여전히 같은 오류를 얻을 수에도 설정하지 않고 나를 못하게하지만 this.setState({isLoggedIn: true}).bind(this)

바인딩을 시도했다.

여기 내 코드

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 { 

} 

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() { 

     if (!this.isLoggedIn) { 

      Actions.welcome(); 

     } 

     firestack.auth.listenForAuth(function(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); 

     } 


    }); 

} 

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); 

내 인터페이스

최초의 내가 여기에 누락이 있나요?

+1

전체 파일을 게시하십시오. 너 어떻게 수업 듣는거야? – bluetoft

+0

큰 누락이있는 것처럼 보입니다 – Maxwelll

답변

3

listenForAuth의 콜백 함수에서 this이 더 이상 MainList 개체를 참조하지 않기 때문에 문제가 발생했습니다. 당신이 화살표 기능에 대한 자세한 내용을 알고 싶다면

firestack.auth.listenForAuth((evt: any) => { 
    ... 
}); 

Here 좋은 읽기입니다 :

하면 this 바인딩 문제를 해결 함수식을 화살표로 전환하십시오.

+0

고맙습니다 .--) 나는 이것을 깨달았어야했지만 나는 조금 새로운 것을 언급하는 것을 잊어 버렸습니다. 그러나 이것은 결국 도움의 도움이되었습니다! –

+0

당신은 오신 것을 환영합니다! 'bind (this)'나'var is = this;')와 같은 몇 가지 다른 해결책이 있지만, 화살표 기능 (ES6에서 소개되었습니다)을 사용하면 훨씬 더 쉽습니다. –

+0

나는 var = this를 할 것이다; 클래스 정의 밖에서 내가 그 일을한다면 내가 모이는거야? –