簡體   English   中英

帶有TypeScript的React Native this.setState不是一個函數

[英]React Native w/ TypeScript this.setState is not a function

我目前正在使用帶有最新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);

我在這里想念什么嗎?

問題是因為在listenForAuth的回調函數中, this不再引用MainList對象。

嘗試切換到箭頭函數表達式來解決this綁定問題:

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

如果您想了解更多有關箭頭功能的信息,請閱讀這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM