代码
const MypageStack = createStackNavigator(
{
News,
Mypage,
},
{
initialRouteName: 'Mypage',
},
);
const postLoginNavigator = createBottomTabNavigator({
Mypage: MypageStack,
});
const AppNavigator = createStackNavigator({
Loading,
First,
PostLogin: postLoginNavigator,
}, {
mode: 'card',
headerMode: 'none',
initialRouteName: 'Loading',
defaultNavigationOptions: {
gestureEnabled: false,
},
});
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
async componentDidMount() {
Notifications.addListener(this.subscribeNotification);
}
subscribeNotification = (notification) => {
const { screen = null } = data;
// screen = 'News'
if (notification.origin === 'selected') {
if (screen) {
dispatch(NavigationActions.navigate({ routeName: screen }));
}
}
}
render() {
return (
<AppContainer />
);
}
}
我要做什么
打开通知时,我要导航到“新闻”屏幕。
但是,dispatch(NavigationActions.navigate({ routeName: screen }));
无效。
我出错了。
找不到变量:调度
我不知道如何导航。如果您能给我任何建议,我将不胜感激。
答案 0 :(得分:0)
要调度导航操作,您必须使用道具中的根导航对象=>
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'HOME_SCREEN' })] });
this.props.navigation.dispatch(resetAction);
但是我发现创建一个名为NavigationService.js
的通用文件来管理您的导航操作更为方便,例如
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
function getCurrentRoute() {
let route = _navigator.state.nav
while (route.routes) {
route = route.routes[route.index]
}
return route
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
getCurrentRoute
};
更新您的<AppContainer/>
,以将导航引用传递到NavigationSerive
文件
<AppContainer ref={ref => NavigationService.setTopLevelNavigator(ref) }
然后在应用程序中的任何位置导入并调用所需的任何内容
import NavigationService from './NavigationService';
NavigationService.navigate(routeName, { ...yourParams })
快乐编码