首页 文章

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

提问于
浏览
1

我目前正在使用React Native 0.39.2 w /最新的TypeScript,当我运行componentDidMount()方法和setState时,我得到一个错误.setState不是一个函数 .

我尝试用 this.setState({isLoggedIn: true}).bind(this) 绑定

虽然因为我使用布尔值作为类型它不会让我没有给出类型错误,甚至设置为任何类型仍然会得到相同的错误 .

这是我的代码

首先是我的State接口

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 回答

  • 3

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

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

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

    如果您想了解更多有关箭头功能的信息,请阅读Here .

相关问题