简体   繁体   English

首次登录时使用React-Native欢迎屏幕

[英]React-Native Welcome Screen on first login

I am developing a React-Native app in which I want to include a Welcome Screen that shows up after the user logs in, but only on the first time. 我正在开发一个React-Native应用程序,我想在其中包含一个欢迎屏幕,该屏幕在用户登录后才出现,但仅限于第一次。 I have already developed the Welcome Screen with React-Native-App-Intro-Slider and it works fine, but it shows up every time the user opens the app. 我已经用React-Native-App-Intro-Slider开发了欢迎屏幕,它可以正常工作,但是每次用户打开应用程序时都会显示。

This is the code I have at the moment. 这是我目前的代码。 This is the Welcome.js code: 这是Welcome.js代码:

import { StyleSheet, View, Text, Image, I18nManager, Dimensions } from 'react-native';
import AppIntroSlider from 'react-native-app-intro-slider';
import { TouchableRipple } from 'react-native-paper'
import FastImage from 'react-native-fast-image';
import Icon from 'react-native-vector-icons/FontAwesome5'
import styles from './Welcome.styles';

I18nManager.forceRTL(false);

const slides = [
    {
        key: 'k1',
        title: '',
        text:
            '',
        video: {
            'id': 'k1',
            'name': '',
            'externalUrl': '',
            'link': '',
            'type': 'video',
            'uuid': 'external',
            'cover_url': '',
            'title-human': '',
            'brand-human': '',
        },
        image: require('../../assets/images/logo.png')
    },
    {
        key: 'k2',
        title: 'Step 1:',
        text: '',
        video: {
            'id': 'k2',
            'name': '',
            'externalUrl': '',
            'link': '',
            'type': 'video',
            'uuid': 'external',
            'cover_url': '',
            'title-human': '',
            'brand-human': '',
        },
        footer: ''
    },
    {
        key: 'k3',
        title: 'Step 2:',
        text: 'Connect your music through your speakers',
        video: {
            'id': 'k3',
            'name': '',
            'externalUrl': '',
            'link': '',
            'type': 'video',
            'uuid': 'external',
            'cover_url': '',
            'title-human': '',
            'brand-human': '',
        },
    }, {
        key: 'k4',
        title: '',
        text: '',
        video: {
            'id': 'k4',
            'name': '',
            'externalUrl': '',
            'link': '',
            'type': 'video',
            'uuid': 'external',
            'cover_url': '',
            'title-human': '',
            'brand-human': '',
        },
    },
    {
        key: 'k5',
        title: 'And lastly...',
        image: require('../../assets/images/logo.png'),
        text: '',
        footer: ''
    }

];

export default class Welcome extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            show_Main_App: false
        }
    }

    static navigationOptions = { header: null }

    on_Done_all_slides = () => {
        this.setState({ show_Main_App: true });
    };


    on_Skip_slides = () => {
        this.setState({ show_Main_App: true });
    };

    _renderItem = ({ item }) => (
        <View style={styles.mainContent}>
            <Text style={styles.title}>{item.title}</Text>
            {item.image == undefined ? (
                <>
                    <View style={styles.videoContainer}>
                        <FastImage style={styles.videoImage} resizeMode='cover' source={{ uri: item.video.cover_url }} />
                        <View style={styles.videoDetailsContainer}>
                            <View style={styles.videoTagContainer}>
                                <Text style={styles.videoTagText}> </Text>
                            </View>
                            <View style={styles.featuredVideoButtonsContainer}>

                                <TouchableRipple
                                    onPress={() => this.props.navigation.navigate({ routeName: 'VideoPlayer', key: 'videoPlayer', params: { 'item': item.video } })}
                                    rippleColor='rgba(0, 0, 0, .32)'
                                >
                                    <View style={styles.videoPlayButton}>
                                        <Icon style={styles.videoPlayButtonIcon} name='play-circle' size={100} color='#fff' />
                                        <Text style={styles.videoPlayButtonText}>Play</Text>
                                    </View>
                                </TouchableRipple>
                            </View>
                        </View>
                    </View>
                    <Text style={styles.text}>{item.text}</Text>
                </>
            ) : (
                    <>
                        <Image source={item.image} style={styles.image} resizeMode='contain' />
                        <View>
                            <Text style={styles.text}>
                                {item.text}
                            </Text>
                            <Text style={styles.text}>
                                {item.footer}
                            </Text>
                        </View>
                    </>
                )}
        </View>
    );

    render() {
        if (this.state.show_Main_App) {
            return (
                this.props.navigation.replace('Dashboard')
            );
        } else {
            return (
                <AppIntroSlider
                    renderItem={this._renderItem}
                    slides={slides}
                    onDone={this.on_Done_all_slides}
                    showSkipButton={true}
                    onSkip={this.on_Skip_slides} />
            );
        }
    }
}

As I said, this works exactly as intended. 正如我所说,这完全符合预期。 However, it shows up every time. 但是,它每次都会显示。 This is my App.js code: 这是我的App.js代码:

import { createStackNavigator, createAppContainer, createBottomTabNavigator } from 'react-navigation'
import { View, StatusBar, Text } from 'react-native'
// import FontAwesome from 'react-native-vector-icons/FontAwesome5'
import IconFontawesome from 'react-native-vector-icons/FontAwesome'
import IconMaterial from 'react-native-vector-icons/MaterialCommunityIcons'
import { MenuProvider } from 'react-native-popup-menu';

// screens
import Splashscreen from './src/screens/Splashscreen/Splashscreen'
import ProfileSetup from './src/screens/ProfileSetup/ProfileSetup'
import UserCreation from './src/screens/UserCreation/UserCreation'
import Login from './src/screens/Login/Login'
import Signup from './src/screens/Signup/Signup'
import VideoPlayer from './src/screens/VideoPlayer/VideoPlayer'
import VideoProfile from './src/screens/VideoProfile/VideoProfile'
import AudioProfile from './src/screens/AudioProfile/AudioProfile'
import ForgotPassword from './src/screens/ForgotPassword/ForgotPassword'
import Welcome from './src/screens/Welcome/Welcome'
import WhoWatching from './src/screens/WhoWatching/WhoWatching'

// Tabs
import MenuScreen from './src/screens/TabScreens/MenuScreen/MenuScreen'
import HomeScreen from './src/screens/TabScreens/HomeScreen/HomeScreen'
// import DownloadScreen from './src/screens/TabScreens/DownloadScreen/DownloadScreen' // avega : replaced with devices screen
import DeviceScreen from "./src/screens/TabScreens/DeviceScreen/DeviceScreen";
import SearchScreen from './src/screens/TabScreens/SearchScreen/SearchScreen'

// Menu Screens
import AccountScreen from './src/screens/TabScreens/MenuScreen/AccountScreen/AccountScreen'
import AppSettingsScreen from './src/screens/TabScreens/MenuScreen/AppSettingsScreen/AppSettingsScreen'
import CellularDataUsageScreen from './src/screens/TabScreens/MenuScreen/AppSettingsScreen/CellularDataUsageScreen/CellularDataUsageScreen'
import VideoQualityScreen from './src/screens/TabScreens/MenuScreen/AppSettingsScreen/VideoQualityScreen/VideoQualityScreen'
import HelpScreen from './src/screens/TabScreens/MenuScreen/HelpScreen/HelpScreen'
import ManageProfilesScreen from './src/screens/TabScreens/MenuScreen/ManageProfilesScreen/ManageProfilesScreen'
import MyListScreen from './src/screens/TabScreens/MenuScreen/MyListScreen/MyListScreen'
import PrivacyScreen from './src/screens/TabScreens/MenuScreen/PrivacyScreen/PrivacyScreen'
import configureStore from "./src/state/store";
import {Provider} from "react-redux";
import {Root} from "native-base";
import DeviceProfile from "./src/screens/DeviceProfile/DeviceProfile";
import DeviceEnroll from "./src/screens/DeviceEnroll/DeviceEnroll";


const DashboardTabNavigator = createBottomTabNavigator(
    {
        HomeScreen: HomeScreen,
        SearchScreen: SearchScreen,
        DeviceScreen: DeviceScreen,
        MenuScreen: MenuScreen
    },
    {
        defaultNavigationOptions: ({ navigation }) => ({
            tabBarIcon: ({ focused, horizontal, tintColor }) => {
                const { routeName } = navigation.state;
                let iconName;

                if (routeName === 'MenuScreen') {
                    iconName = `menu`
                } else if (routeName === 'HomeScreen') {
                    iconName = `home`
                } else if (routeName === 'DeviceScreen') {
                    iconName = `television`;
                } else if (routeName === 'SearchScreen') {
                    iconName = `thermometer`
                }
                // return <IconFontawesome name={iconName} size={30} color={focused ? '#fff' : '#c0d3d6'} />
                return <IconMaterial name={iconName} size={30} color={focused ? '#fff' : '#c0d3d6'} />
            },
            tabBarLabel: ({ focused, tintColor }) => {
                const { routeName } = navigation.state;
                let labelName;
                if (routeName === 'MenuScreen') {
                    labelName = `Menu`
                } else if (routeName === 'HomeScreen') {
                    labelName = `Showcase`
                } else if (routeName === 'DeviceScreen') {
                    labelName = `Devices`
                } else if (routeName === 'SearchScreen') {
                    labelName = `Store`
                }
                return <Text style={focused ? { textAlign: 'center', fontSize: 11, color: '#fff', fontWeight: '600', marginTop: -5, marginBottom: 5 } : { textAlign: 'center', fontSize: 11, marginTop: -5, marginBottom: 5, color: '#C0D3D6' }}>{labelName}</Text>
            }
        }),
        tabBarOptions: {
            activeTintColor: '#ff3402',
            inactiveTintColor: '#eaeaea',
            style: {
                backgroundColor: '#00A5AC',
                height: 65
            },
            labelStyle: {
                color: '#fff'
            }
        },
        initialRouteName: 'HomeScreen',
        navigationOptions: {
            header: null
        }
    }
)

const AppNavigator = createStackNavigator(
    {
        Splashscreen: Splashscreen,
        UserCreation: UserCreation,
        Login: Login,
        Signup: Signup,
        ProfileSetup: ProfileSetup,
        Dashboard: DashboardTabNavigator,
        Account: AccountScreen,
        AppSettings: AppSettingsScreen,
        VideoQuality: VideoQualityScreen,
        CellularDataUsage: CellularDataUsageScreen,
        Help: HelpScreen,
        ManageProfiles: ManageProfilesScreen,
        MyList: MyListScreen,
        Privacy: PrivacyScreen,
        VideoPlayer: VideoPlayer,
        VideoProfile: VideoProfile,
        AudioProfile: AudioProfile,
        //AudioPlayer: AudioPlayer
        ForgotPassword: ForgotPassword,
        WhoWatching: WhoWatching,
        DeviceProfile: DeviceProfile,
        DeviceEnroll: DeviceEnroll,
        Welcome: Welcome
    },
    {
        initialRouteName: 'Splashscreen',
        navigationOptions: {
            header: null
        }
    }
);

const AppContainer = createAppContainer(AppNavigator)

export default class App extends React.Component {
    store = configureStore();

    render () {

        return (
            <Provider store={this.store}>
                <Root>
                    <MenuProvider>
                        <View style={{ flex: 1 }}>
                            <AppContainer />
                            <StatusBar translucent backgroundColor='transparent' barStyle='light-content' />
                        </View>
                    </MenuProvider>
                </Root>
            </Provider>
        )
    }
}

As you can see the first page is a Splashscreen, that then should lead to the guided tour. 如您所见,第一页是启动画面,然后将引导您进行导览。 This is the Splashscreen.js code: 这是Splashscreen.js代码:

import { View, Image, ActivityIndicator } from 'react-native'
import styles from './Splashscreen.styles'
import AuthHelperMethods from "../../api/auth-helper-methods";
export default class Splashscreen extends Component {
  static navigationOptions = { header: null }
  componentDidMount () {
    setTimeout(() => {
      AuthHelperMethods.loggedIn().then((isLoggedIn) => {
        if (isLoggedIn) {
          this.props.navigation.replace('Welcome')
        } else {
          this.props.navigation.replace('UserCreation')
        }
      })
    }, 500)
  }
  state={ 
    loading: true
  };

  render () {
    return (
      <View style={styles.container}>
        <Image style={styles.logo} resizeMode='contain' source={require('../../assets/images/logo.png')} />
        <ActivityIndicator size={50} color='#00b2ba' />
      </View>
    )
  }
}

I'm not really sure how to start conceptualizing the idea of this component only showing up either on first-time login, or at least once per login instead of every time the app is used. 我不太确定如何开始概念化该组件的概念,仅在首次登录时显示,或者在每次登录时(而不是在每次使用该应用程序时)至少显示一次。

Any ideas how to go about it? 任何想法如何去做?

You can use Shared Preferences to check if it is the first login. 您可以使用“共享首选项”来检查它是否是首次登录。

Simply store a boolean like showWelcomeScreen when the welcome screen was shown. 显示欢迎屏幕时,只需存储一个类似于showWelcomeScreenboolean On startup you can check the shared preferences and decide wheter to show or not to show the screen. 启动时,您可以检查共享的首选项,然后决定是显示还是不显示屏幕。

For more information check: Shared Preferences 有关更多信息,请检查: 共享首选项

You can simply use localStorage . 您可以简单地使用localStorage You will have to do some conditional rendering. 您将必须执行一些条件渲染。 Whenever user launches the app, you will have to do something like localStorage.setItem('firstTime', false) . 每当用户启动应用程序时,您都必须执行类似localStorage.setItem('firstTime', false) So, next time when user launches the app, all you need is check if localStorage.getItem('firstTime') === false , if it is false, you render your login page . 因此,下次用户启动应用程序时,您需要检查localStorage.getItem('firstTime') === false ,如果为false,则呈现登录页面

The easiest way is probably using asyncStorage ( https://facebook.github.io/react-native/docs/asyncstorage ) 最简单的方法可能是使用asyncStoragehttps://facebook.github.io/react-native/docs/asyncstorage

After installing it import it like: 安装后将其导入,如下所示:

import AsyncStorage from '@react-native-community/async-storage';

or 要么

import {AsyncStorage} from 'react-native'   //Deprecated, will be removed in the future

After you've showed the user the welcome screen, store the data inside asyncStorage : 向用户显示欢迎屏幕后,将数据存储在asyncStorage

storeData = async () => {
  try {
    await AsyncStorage.setItem('welcomeScreenSeen', 'true')
  } catch (e) {
    // saving failed
  }
}

After that, ever login would check that variable and if it's false, just skip your welcomeScreen. 之后,每次登录都会检查该变量,如果为假,则跳过您的welcomeScreen。

then inside your isLoggedInIf it would be: 然后在您的isLoggedIn中,如果是:

if (isLoggedIn) {
      this.props.navigation.replace(this.getData("welcomeScreenSeen")?'ScreenDifferentFromWelcome':'Welcome')
    }

where getData would be: getData在哪里:

getData = async (key) => {
  try {
    const value = await AsyncStorage.getItem(key)
    return value
  } catch(e) {
    // error reading value
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM