2016-12-24 62 views
1

我目前使用React Native 0.39.2 w/newest TypeScript,当我运行我的componentDidMount()方法和setState时,我得到一个错误this.setState不是一个函数。React Native w/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 that = this;'),但是我发现使用箭头函数(ES6中引入的)更容易。 –

+0

我会做var = this;在课堂定义之外,如果我要这样做,我正在聚会? –

相关问题