在react-native app中加载主屏幕之前显示模态

时间:2017-01-05 04:17:11

标签: javascript reactjs react-native

我试图在我的主屏幕加载我的react-native应用程序之前显示一个非动画模式。基本上我想检查用户是否登录,如果没有登录用户在模态视图上显示登录屏幕。

问题是我的主屏幕在我的模态之前瞬间显示,而不是先显示模态。我是新手反应/ javascript一般,我不知道如何解决这个问题。

我将登录检查放在componentWillLoad中,认为这会在组件在屏幕上呈现之前发生,但它似乎无法正常工作。

export default class MyClass extends Component {

  state = {
    modalVisible: false,
  }

  componentWillMount() {
    // Check if a user is signed in
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        console.log("Signed in");
        this.setState({modalVisible: false});
      } else {
        // No user is signed in.
        console.log("Not signed in");
        this.setState({modalVisible: true});
      }
    }.bind(this));
  }

  render() {

    return (
      <View>

        <NavigatorIOS
          initialRoute={{
            component: Things,
            title: 'MyScene',
          }}
          style={{flex: 1}}
        />

        <Modal
          animationType={"none"}
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {alert("Modal has been closed.")}}
          >
          <Login />
        </Modal>

      </View>

    );

  }
}

1 个答案:

答案 0 :(得分:3)

它出现了一瞬间,因为onAuthStateChanged调用是asynchronous并且react不会等待它完成并继续运行,因此你的渲染会在firebase返回之前发生。所以要解决这个问题,你必须等到firebase返回。要实现这一点,让我们使用状态。将创建一个名为isFirebaseReturned的状态变量。在下面的代码中react仅在NavigatorIos

时呈现ModalisFirebaseReturned = true
export default class MyClass extends Component {

  state = {
    modalVisible: false,
    isFirebaseReturned:false
  }

  componentWillMount() {
    // Check if a user is signed in
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        console.log("Signed in");
        this.setState({modalVisible: false,isFirebaseReturned:true});
      } else {
        // No user is signed in.
        console.log("Not signed in");
        this.setState({modalVisible: true,isFirebaseReturned:true});
      }
    }.bind(this));
  }

  render() {

    return (
      <View>
      {this.state.isFirebaseReturned &&
        <NavigatorIOS
          initialRoute={{
            component: Things,
            title: 'MyScene',
          }}
          style={{flex: 1}}
        />

        <Modal
          animationType={"none"}
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {alert("Modal has been closed.")}}
          >
          <Login />
        </Modal>
      }
      </View>

    );

  }
}