React-Native:在wix / react-native-navigation中启动有条件的应用程序-v1

时间:2019-04-17 15:48:50

标签: react-native wix-react-native-navigation

我在我的React Native项目中使用wix/react-native-navigation - v1,并且我希望根据以下条件启动我的应用程序:

  • 启动应用
  • 从存储(AsyncStorage)中读取凭据
  • 如果找到凭据,则
    • 使用主屏幕启动应用程序
  • 其他
    • 使用登录屏幕启动应用程序

我该如何实现?

我有 index.js

import App from './App';

App.js

...
Navigation.registerComponent("myApp.AuthScreen", () => AuthScreen);
Navigation.registerComponent("myApp.HomeScreen", () => HomeScreen);
...

// Start a App
Navigation.startSingleScreenApp({
    screen: {
        screen: "myApp.AuthScreen",
        title: "Login"
    }
});

3 个答案:

答案 0 :(得分:1)

您可以使用两种功能来初始化单屏应用程序,然后调用满足要求的功能。

...
Navigation.registerComponent("myApp.AuthScreen", () => AuthScreen);
Navigation.registerComponent("myApp.HomeScreen", () => HomeScreen);
...

function startHomeScreen() {
Navigation.startSingleScreenApp({
    screen: {
        screen: "myApp.HomeScreen",
        title: "Login"
    }
});
}

function startAuthScreen() {
Navigation.startSingleScreenApp({
    screen: {
        screen: "myApp.AuthScreen",
        title: "Home"
    }
});
}

function init() {
   if(...) {
      startAuthScreen();
   } else {
      startHomeScreen();
   }
}

答案 1 :(得分:1)

成功了!我不确定为什么该应用程序一直挂在启动屏幕上。以下是确切的代码:

const __init__ = () => {
    try {
        AsyncStorage.getItem("MY-KEY")
            .then((value) => {
                if (value) {
                    startHomeScreen();
                } else {
                    startAuthScreen();
                }
            });
    } catch (e) {
        startAuthScreen();
    }
};
__init__();

感谢@Filip Ilievski!

答案 2 :(得分:0)

Navigation.registerComponent("RootScreen", () => RootScreen);

Navigation.startSingleScreenApp({
    screen: {
        screen: "RootScreen",
        title: "Root"
    }
});

对于这种情况,您可以创建一个其他组件,如下所示。 这个额外的组件将检查您在异步存储中的状况,并确定首先加载哪个视图

import AuthScreen from './AuthScreen';
import HomeScreen from './HomeScreen';

class RootScreen {
  constructor(props) {
    super(props);
    this.state = {
      loaded: false,
      screenToLoad: ''
    };
  }

  componentDidMount() {
    this.checkRoute();
  }

  checkRoute = () => {
    AsyncStorage.getItem("MY-KEY")
      .then((value) => {
        this.setState({
          loaded: true,
          screenToLoad: value
        });
      });
  }

  renderRoute = () => {
    const { screenToLoad } = this.state;
    switch(screenToLoad) {
      case 'AuthScreen':
        return <AuthScreen />;

      case 'HomeScreen':
        return <HomeScreen />

      default:
        return null;
    }
  }

  render () {
    const { loaded } = this.state;
    if (!loaded) return null;
    return this.renderRoute();
  }
}