我的应用场景是这样的,假设你有三个组件:
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
中是否有任何内置方法?去做这个?谁能告诉?示例将更受欢迎。谢谢!
最佳答案
所有导航器都有 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
Action - 当组件挂载时,您检查是否已保存
AsyncStorage
中的路由
- 如果有路由,则发送导航操作(也可以实现替换操作)
希望对您有所帮助。
关于android - 如何使用 react 导航在 react native 中加载相同的最后一个组件类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262763/