Firebase 在非组件类的屏幕之间进行本机导航
我正试图在后台类的react本机屏幕之间导航,如下所示:Firebase 在非组件类的屏幕之间进行本机导航,firebase,react-native,firebase-authentication,react-navigation,stack-navigator,Firebase,React Native,Firebase Authentication,React Navigation,Stack Navigator,我正试图在后台类的react本机屏幕之间导航,如下所示: var self = this; firebase.auth().onAuthStateChanged((user) => { if (user) { self.setState({ userID: user.uid, }) } else{ self.props.navigation.navigate("Login"); } }); 我的后端类不是组件,因此不会导入到我正
var self = this;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
self.setState({
userID: user.uid,
})
} else{
self.props.navigation.navigate("Login");
}
});
我的后端类不是组件,因此不会导入到我正在使用的堆栈导航器中。我在说“self.props.navigation不是对象”时出错
有人知道我能解决这个问题吗?谢谢一个不太好的做法是将导航器定义为应用程序实例的静态/类变量:
const MyNavigator = StackNavigator(...);
export default class MyApp extends Component {
render() {
return <MyNavigator ref={(ref) => MyApp.Navigator = ref}/>
}
}
我个人不喜欢在这个级别上进行导航操作,但是,有时这是必要的。在@Dash的答案基础上,我了解了一种模式,这有助于解决这个问题。你可以在这里找到它
这样做的目的是创建一个服务,其中包含对导航器的引用。现在,您可以从应用程序中的任何位置导入该服务并访问导航器。它保持了它的整洁和简洁。如果您使用的是react导航,那么您可以通过导航服务实现这一点 创建一个名为NavigationService的文件,并在其中添加以下代码 现在在app.js中导入此文件并设置TopLevelNavigator,您的app.js将如下所示
import MyApp from '...';
MyApp.Navigator.dispatch(NavigationActions.back());
import { NavigationActions, StackActions } from 'react-navigation';
let navigator;
function setTopLevelNavigator(navigatorRef) {
navigator = navigatorRef;
}
function navigate(routeName, params) {
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
}
function goBack(routeName, params) {
navigator.dispatch(
StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName,
params
})
]
})
);
}
function replace(routeName, params) {
navigator.dispatch(
StackActions.replace({
index: 0,
actions: [
NavigationActions.navigate({
routeName,
params
})
]
})
);
}
function pop() {
navigator.dispatch(StackActions.pop());
}
function popToTop() {
navigator.dispatch(StackActions.popToTop());
}
// add other navigation functions that you need and export them
export default {
navigate,
goBack,
replace,
pop,
popToTop,
setTopLevelNavigator
};
import React, { Component } from 'react';
import NavigationService from './routes/NavigationService';
export default class App extends Component {
constructor() {
super();
}
render() {
return (
<View style={{ flex: 1, backgroundColor: '#fff' }}>
<AppNavigator
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
</View>
);
}
}
import NavigationService from 'path to the NavigationService file';
/* you can use any screen name you have defined in your StackNavigators
* just replace the LogInScreen with your screen name and it will work like a
* charm
*/
NavigationService.navigate('LogInScreen');
/*
* you can also pass params or extra data into the ongoing screen like this
*/
NavigationService.navigate('LogInScreen',{
orderId: this.state.data.orderId
});