我的应用场景就像,假设您有三个组成部分:
class ComponentOne extends Component {
render() {
return (
<View>
<Text>Component One</Text>
<Button
title='Go To Component Two'
onPress={() => this.props.navigation.navigate('two')}/>
</View>
);
}
}
class ComponentTwo extends Component {
render() {
return (
<View>
<Text>Component Two</Text>
<Button
title='Go To Component Three'
onPress={() => this.props.navigation.navigate('three')}/>
</View>
);
}
}
class ComponentThree extends Component {
render() {
return (
<View>
<Text>Component Three</Text>
<Button
title='Go To Component One'
onPress={() => this.props.navigation.navigate('one')}/>
</View>
);
}
}
export default createStackNavigator({one: ComponentOne,two: ComponentTwo,three: ComponentThree});
现在,当我加载应用程序时,ComponentOne
将被加载,在ComponentOne
内部,当我单击按钮Go To Component Two
时,它将导航到ComponentTwo
,内部ComponentTwo
,当我点击按钮Go To Component Three
时,它将导航至ComponentThree
,依此类推。现在说我在ComponentTwo
中,同时关闭手机中的应用程序,然后打开应用程序切换器并清理所有正在运行的应用程序,然后再次加载同一应用程序,因此,它将再次加载ComponentOne
。
我的问题是,即使从后台清理应用程序(清理应用程序切换器中的所有应用程序),如何对react navigation
进行编程,使其从我上次离开的同一组件继续执行?
react navigation
中是否有任何内置方法可以做到这一点?谁能告诉?实例将被更多地理解。谢谢!
答案 0 :(得分:1)
我不认为直接使用react-navigation有解决方案。 我想您可以做的是将当前屏幕的值保存到手机的存储器中,然后在应用程序启动时使用该值来检测要显示的屏幕
答案 1 :(得分:1)
所有导航器都有onNavigationStateChange
,您可以在其中处理导航状态更改。示例代码:
import React from 'react';
import { AsyncStorage } from 'react-native';
import { createStackNavigator, NavigationActions } from 'react-navigation';
const Navigator = createStackNavigator({
ComponentOne: {
screen: ComponentOne,
},
ComponentTwo: {
screen: ComponentTwo,
},
ComponentThree: {
screen: ComponentThree,
},
}, {
initialRouteName: 'ComponentOne',
});
class App extends Component {
constructor(props) {
this.navigator = React.createRef();
}
componentDidMount() {
try {
// Retrieve the last route
const value = AsyncStorage.getItem('lastNavigationRoute').then((result) => {
if (result) {
this.navigator.current.dispatch(NavigationActions.navigate({
routeName: result,
}));
}
});
} catch (e) {
// handle the error
}
}
handleStateChange = (previousState, nextState) => {
// Here we get the Navigate action type only
const navigateAction = NavigationActions.navigate({ routeName: 'dummyRoute' });
if (action.type === navigateAction.type) {
try {
// Saving the last route
AsyncStorage.setItem('lastNavigationRoute', nextState.routeName);
} catch (e) {
// handle the error
}
}
}
render() {
// You could also set a state with loader to handle loading from AsyncStorage
return (
<Navigator onNavigationStateChange={this.handleStateChange} ref={this.navigator} />
);
}
}
工作原理:
routeName
来自Navigate
行动AsyncStorage
希望有帮助。