首先,您需要在 TabNavigator 配置中激活惰性选项,例如:
const AppNavigator = TabNavigator(
{
Home: { screen: HomeScreen },
LoginScreen: { screen: LoginScreen },
/* the screen needed auth */
AddPost: {screen: AddPostScreen},
...
},
{
lazy: true,
...
})
其次,我添加了这个包react-navigation-is-focused-hoc
$ yarn add react-navigation-is-focused-hoc
它用于检查活动屏幕,在反应渲染 AppNavigator 上添加一些道具:
...
import { updateFocus } from 'react-navigation-is-focused-hoc';
...
return (
...
<AppNavigator
onNavigationStateChange={(prevState, currentState) => {
updateFocus(currentState);
}}
/>
...
);
最后,将isFocused添加到您的 Authenticated 屏幕 (AddPostScreen):
import { withNavigationFocus } from 'react-navigation-is-focused-hoc';
...
@withNavigationFocus('AddPostScreen')
class AddPostScreen extends React.Component {
static navigationOptions = () => ({
/* Your navigation options */
})
componentWillReceiveProps(nextProps) {
const { isFocused, auth: { signedIn }, navigation: { navigate } } = this.props;
if (!isFocused && nextProps.isFocused && !signedIn) {
navigate('LoginScreen');
}
}
shouldComponentUpdate(nextProps) {
const { isFocused } = this.props;
if (isFocused && !nextProps.isFocused) {
return true;
}
// Don't update if the screen is not focused
if (!isFocused && !nextProps.isFocused) {
return false;
}
// Update the screen if its re-enter
return !isFocused && nextProps.isFocused;
}
render() {
return (
/* return authenticated component */
...
signedIn (boolean) 是来自您的 auth reducer 的状态