ReactNative:仅在导航到新页面完成后禁用活动指示器

时间:2018-04-20 19:47:03

标签: react-native react-native-android react-native-navigation activity-indicator stack-navigator

我是React Native的新手。我已经编写了一个登录页面和个人资料页面。

在Login.js页面上我说:

this.state = {
  email: '',
  password: '',
  authenticating: false,
}

输入正确的详细信息后点击“登录”按钮后,将执行loginUser函数:

loginUser = (email, password) => {
this.setState({ authenticating: true });
try {
  firebase.auth().signInWithEmailAndPassword(email, password)
    .then((user) => {
      this.props.navigation.navigate('Profile');
      this.setState({ authenticating: false });
    });
}
catch (error) {
  console.log(error.toString());
  }
}

以下是我的渲染功能:

renderCurrentState() {
if (this.state.authenticating) {
  return (
    <View>
      <ActivityIndicator size='large' />
    </View>
  )
}

return (
  <View>
    <Input
      placeholder='Enter your Email...'
      label='Email'
      onChangeText={email => this.setState({ email })}
      value={this.state.email}
    />
    <Input
      placeholder='Enter your Password...'
      label='Password'
      secureTextEntry
      onChangeText={password => this.setState({ password })}
      value={this.state.password}
    />
    <Button
      onPress={() => this.loginUser(this.state.email, this.state.password)}
    >Log in</Button>

    <Button
      onPress={() => this.signUpUser(this.state.email, this.state.password)}
    >Sign upp</Button>

  </View>
)
}

问题是,一旦我点击登录按钮,它就会开始显示活动指示器,但在显示&#39;个人资料&#39;之前它会显示“登录”页面。页面再次持续几毫秒,我不想要。

对此有任何帮助。我不想像这样放一个setTimeOut延迟解决方案:

setTimeout(()=>{  this.setState({ authenticating: false }) }, 100)

如果有人可以为我提供代码。这将非常有帮助。

1 个答案:

答案 0 :(得分:1)

React-navigation now has lifecycle hooks. You can wait for current screen to blur so that you know the transition has completed.

  navigateAsync = (routeName) => {
    const promise = new Promise(resolve => {
      const subscription = this.props.navigation.addListener('didBlur', () => {
        subscription.remove();
        resolve();
      });
    });
    this.props.navigation.navigate(routeName);
    return promise;
  };

And then you can just call

this.navigateAsync('Profile').then(() => {
  this.setState({ authenticating: false });
})

See https://github.com/react-navigation/rfcs/issues/11