使用Firebase反应导航身份验证流程。没有预期的重新渲染

时间:2020-06-27 15:26:48

标签: firebase react-native react-navigation

我正在尝试使用react导航和firebase创建一个登录屏幕。 在https://reactnavigation.org/docs/auth-flow/之后,我在ComponentDidMount中使用Firebase侦听器创建了一个身份验证流,当Firebase身份验证发生更改时,该身份流应会更改状态。据我了解,状态更改应导致重新渲染并导航至所需的“经过身份验证”的堆栈。但是我无法使其正常工作,似乎没有重新渲染。有时我还会收到错误“在未安装的组件上触发”。我在想,也许这与听众的位置有关。是否应该处于React生命周期的不同阶段?也许与setState的异步特性有关。

const Stack = createStackNavigator();

export default class App extends Component {

  constructor(props){
    this.state = {auth: false};
  }

  componentDidMount(){
  //on auth state change
    firebase.auth().onAuthStateChanged((user) =>{
      if (user) {
          this.setState({auth: true})
      } else {
        this.setState({auth: false})
      }
    }); 
  }
  
  render(){
    const {auth} = this.state;
      return (
         <View style={styles.container}>
           {Platform.OS === 'ios' && <StatusBar barStyle="dark-content" />}
             <NavigationContainer linking={LinkingConfiguration}>
                {auth === true ? (
                  <Stack.Navigator>
                    <Stack.Screen name="RootAuth" component={BottomTabNavigatorAuth} />
                    <Stack.Screen name="Root" component={BottomTabNavigator} />
                    <Stack.Screen name="PatientScreen" component={PatientScreen}/>
                  </Stack.Navigator>
                ):(
                  <Stack.Navigator>
                    <Stack.Screen name="Root" component={BottomTabNavigator} />
                    <Stack.Screen name="RootAuth" component={BottomTabNavigatorAuth} />
                  </Stack.Navigator>
                )}
             </NavigationContainer>
          </View>
      );
    }
  }

0 个答案:

没有答案