React Native w / TypeScript this.setState不是函数

时间:2016-12-24 02:37:04

标签: reactjs typescript react-native typescript2.0

我目前正在使用React Native 0.39.2 w /最新的TypeScript,当我运行componentDidMount()方法和setState时,我得到一个关于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 个答案:

答案 0 :(得分:3)

问题是因为在listenForAuth的回调函数中,this不再引用MainList对象。

尝试切换到解决this绑定问题的箭头函数表达式:

firestack.auth.listenForAuth((evt: any) => {
  ...
});
如果您想了解有关箭头功能的更多信息,

Here是一个很好的阅读。