首页 > 解决方案 > 在 React Drawer Navigatoin 中使用带有 Firebase 的 switch 运算符

问题描述

我有一个抽屉导航,我只想根据 firebase 实时数据库中的条件显示某些屏幕,但下面的函数返回未定义。这是在博览会 React Native 中。

function getType(){

  Firebase.database().ref('allTeachers/' + Firebase.auth().currentUser.uid + '/name')
  .once('value').then(function(snapshot){

    return snapshot.exists()
  })
}

这是我要使用此功能结果的导航器。导航器位于功能组件内

!user ? (
            <Drawer.Screen name = "Log In" component={SignUp}/>
            ):getType() ?(

              <>
              <Drawer.Screen name = "Session Creation" component={TeacherSession} />
              <Drawer.Screen name = "Activate Session" component={StartSession} />
              <Drawer.Screen name = "Teacher Details" component={TeacherDetails} />
              <Drawer.Screen name = "Sign Out" component={SignOut} />

              </>
            ):(

                <>
                <Drawer.Screen name = "Student Details" component={StudentDetails} />

                <Drawer.Screen name = "Sign Out" component={SignOut} />
                </>
            )}

我希望能够根据路径是否存在在两种情况之间切换,有人可以帮我吗?

谢谢

标签: javascriptreactjsfirebasereact-nativeauthentication

解决方案


函数 getType() 没有返回语句,因此它永远不会返回值。为了实现你想要的,你必须异步管理它。一种简单的实现方法是使用状态。

假设保存导航器的组件是功能性组件,则以下内容应该有效

const [exists, setExists] = useState(false);

function getType(){

  Firebase.database().ref('allTeachers/' + Firebase.auth().currentUser.uid + '/name')
  .once('value').then(function(snapshot){

    setExists(snapshot.exists());
  })
}

React.useEffect(() => {
    getType();
}, []);

...

!user ? (
            <Drawer.Screen name = "Log In" component={SignUp}/>
            ):exists ?(

              <>
              <Drawer.Screen name = "Session Creation" component={TeacherSession} />
              <Drawer.Screen name = "Activate Session" component={StartSession} />
              <Drawer.Screen name = "Teacher Details" component={TeacherDetails} />
              <Drawer.Screen name = "Sign Out" component={SignOut} />

              </>
            ):(

                <>
                <Drawer.Screen name = "Student Details" component={StudentDetails} />

                <Drawer.Screen name = "Sign Out" component={SignOut} />
                </>
            )}

推荐阅读