繁体   English   中英

React Native + TypeScript,无法设置状态

[英]React Native + TypeScript, can't set State

我知道我的功能正在运行,但是由于任何原因我都无法设置此属性“ isLoggedIn”的状态

在componentDidMount()中,我基于登录检测设置了setState,它似乎不起作用。

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 {
   isLoggedIn?: boolean;
}

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() {

      firestack.auth.listenForAuth((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);

        }

        if (!this.isLoggedIn) {

            Actions.welcome();

        }


    }); 

}

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);

我做错了什么吗?

    this.setState({isLoggedIn: false});
    console.log("The state of isLoggedIn is: " + this.isLoggedIn);

此代码将不起作用。 setState是异步的,因此不一定要在调用setState之后立即更新this.isLoggedIn 如果要立即访问新值,请使用在设置状态时触发的回调:

this.setState({ isLoggedIn: false }, () => console.log(this.state.isLoggedIn));

或者,使用这种设置状态的方法:

this.setState(oldState => {
    oldState.isLoggedIn = false;

    console.log(oldState.isLoggedIn);
    return oldState;
}); 

在componentDidMount中获取数据。 当响应到达时,通过在回调内部调用setstate将数据存储在state中。

挂载组件后立即调用componentDidMount()。 需要DOM节点的初始化应在此处进行。 如果需要从远程端点加载数据,这是实例化网络请求的好地方。 在此方法中设置状态将触发重新渲染。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM