0

我试图弄清楚如何进行编码。我使用 React Navigation TabNavigator 作为我的主要导航器,并且还使用 Redux 来管理我的应用程序和用户的身份验证状态。

其中一个选项卡的内容只有在用户登录时才能显示,所以我想做的是当他们按下该选项卡时,如果他们尚未登录,我想重定向到或在顶部弹出一个模式带有登录/注册屏幕。在他们成功登录并下拉他们的内容后,我想在他们最初尝试查看的选项卡中显示屏幕。那么你会怎么做呢?

根据我对 TabNavigator 的理解,在初始加载之后,每次单击该选项卡时 componentWillMount 都不会运行,因此我无法在那里检查我的身份验证状态并做出反应。

有没有办法以其他方式拦截选项卡按下并能够在加载该选项卡的视图之前从那里检查我的身份验证状态?

4

1 回答 1

0

首先,您需要在 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 的状态

于 2018-01-15T09:17:30.787 回答