【问题标题】:React Native w/ TypeScript this.setState is not a function带有 TypeScript 的 React Native this.setState 不是一个函数
【发布时间】:2016-12-24 02:37:04
【问题描述】:

我目前正在使用带有最新 TypeScript 的 React Native 0.39.2,当我运行我的 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);

这里有什么我遗漏的吗?

【问题讨论】:

  • 发布您的整个文件。你是如何宣布你的班级的?
  • 看起来你缺少很多东西

标签: reactjs typescript react-native typescript2.0


【解决方案1】:

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

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

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

Here 是一本好书,如果您想了解更多关于箭头函数的信息。

【讨论】:

  • 非常感谢 :-) 我应该意识到这一点,但我忘了说我有点新,但这帮助很大,尤其是最后的帮助参考!
  • 不客气!还有一些其他解决方案(例如bind(this)var that = this;),但我发现使用箭头函数(在 ES6 中引入)更容易。
  • 我会做 var that = this;如果我要这样做我正在收集的类定义之外?
  • 可以在componentDidMount()函数中定义var that = this;,然后在回调函数中使用that.setState()
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 2020-11-01
  • 2015-09-11
相关资源
最近更新 更多