2016-12-24 16 views
1

現在、React Native 0.39.2を使用しています。最新のTypeScriptを使用していて、componentDidMount()メソッドとsetStateを実行するとthis.setState機能。ネイティブ(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オブジェクトを参照していないためです。

this結合の問題を解決するための関数式の矢印に切り替えてみてください。

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

Hereを使用すると、矢印の機能についての詳細をお知りになりたい場合は良い読み物です。

+0

ありがとうございます:-) 私はこれを実現する必要がありますが、私は少し新しいことを忘れていましたが、これは、 –

+0

あなたは大歓迎です!他にもいくつかの解決策があります(例えば 'bind(this)'や 'var is = this;')。しかし、これはES6で導入されたarrow関数を使う方がずっと簡単です。 –

+0

私はvar = thisを実行しますか?クラス定義の外側で、私がそれをしなければならなかったら私は集まっていますか? –

関連する問題