React-navigation在屏幕中获取当前导航状态
问题描述:
我需要能够从我的注册屏幕组件中获取当前导航状态。我期望在navigation.state
对象内找到一个routes
对象,但可惜它不在那里。我已经设法通过以下方式设置我的根组件来实现这个工作,但是这看起来令人费解,我不能帮助,但认为必须有一个更清晰的方式来实现这一点。React-navigation在屏幕中获取当前导航状态
App.js
import React, {Component} from 'react'
import {Tabs} from './components/Routes'
import {NavigationActions} from 'react-navigation'
export default class App extends React.Component {
state = {
navState: null
}
componentDidMount(){
const initState = Tabs.router.getStateForAction(NavigationActions.init())
this.getState(null, initState);
}
getState = (prevState, newState) => {
let activeIndex = newState.index
let navState = newState.routes[activeIndex]
this.setState({navState})
}
render() {
return (
<Tabs
onNavigationStateChange={this.getState}
screenProps={{navState: this.state.navState}}/>
)
}
}
答
<NavigationName
onNavigationStateChange={(prevState, newState) => {
this._getCurrentRouteName(newState)
}}
/>
_getCurrentRouteName(navState) {
if (navState.hasOwnProperty('index')) {
this._getCurrentRouteName(navState.routes[navState.index])
} else {
console.log("Current Route Name:", navState.routeName)
this.setState({navState: setCurrentRouteName(navState.routeName)})
}
}
这是伟大的,但它并不包括如何让导航状态下,应用程序初始化时。这可能吗? – Samuel
componentDidMount(){alert(this.props.navigation.state.key)}它适合你吗? –
林不知道你的意思,我需要在我的根组件中获得我的初始导航状态,然后分派任何导航操作。这就是我的例子中'const initState = Tabs.router.getStateForAction(NavigationActions.init())'所做的事情。 onNavigationStateChange'仅当导航状态如专业名称所示更改时触发。 – Samuel