【问题标题】:How can I navigate to a specific screen when navigation stack is empty?当导航堆栈为空时,如何导航到特定屏幕?
【发布时间】:2019-03-02 13:21:32
【问题描述】:
我该怎么做:
if navigation stack is not empty
this.props.navigation.goBack()
else
this.props.navigation.navigate('CustomScreen')
【问题讨论】:
标签:
react-native
react-navigation
【解决方案1】:
解决方法是从前一个屏幕发送参数并在当前屏幕检查该参数是否存在
屏幕1:
this.props.navigation.navigate('Screen2', {prevScreen: 'Screen1'});
屏幕2:
if(this.props.navigation.getParam('prevScreen', null))
this.props.navigation.goBack();
else
this.props.navigation.navigate('CustomScreen');
【解决方案2】:
this.props.navigation 中有一个名为dangerouslyGetParent 的函数。您可以在文档here 中看到它。
它在文档中声明了以下内容:
另一个很好的用例是找到活动的索引
父路由列表中的路由。所以在堆栈的情况下,如果你是
在索引 0 处,您可能不想呈现后退按钮,但如果
您在列表中的其他位置,然后您将呈现一个后退按钮。
所以我们可以使用下面的方法来获取路线的索引
this.props.navigation.dangerouslyGetParent().state.index
因此,无需传递参数,您就可以检查您在堆栈中的位置,然后决定要做什么。
// get the index of the route
let index = this.props.navigation.dangerouslyGetParent().state.index;
// handle the index we get
if (index > 0) {
this.props.navigation.goBack();
} else {
this.props.navigation.navigate('CustomScreen')
}