简体   繁体   English

Navigator & AsyncStorage 反应原生

[英]Navigator & AsyncStorage react native

Hello i'm new in react native and currently learn about AsyncStorage.您好,我是 React Native 的新手,目前正在了解 AsyncStorage。

I want to implement conditional to render navigator.我想实现条件渲染导航器。 If there's value key in AsyncStorage, the initial route go to Page2 and if there's no value key in AsyncStorage, the initial route go to Page1.如果 AsyncStorage 中有 value key,则初始路由到 Page2,如果 AsyncStorage 中没有 value key,则初始路由到 Page1。

If i close the app and re-open again, I want it shows me the corresponding page whether there is a key.如果我关闭应用程序并再次重新打开,我希望它显示相应的页面是否有密钥。 please help.请帮忙。

Here's what i've done so far:这是我到目前为止所做的:

 import React, { Component } from 'react'; import { AppRegistry, TextInput, StyleSheet, Text, View, Navigator, TouchableOpacity, AsyncStorage, } from 'react-native'; var initialRoute = {id: 1} var STORAGE_KEY = '@AsyncStorageExample:key'; var SCREEN_WIDTH = require('Dimensions').get('window').width; var BaseConfig = Navigator.SceneConfigs.FloatFromRight; var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, { snapVelocity: 8, edgeHitWidth: SCREEN_WIDTH, }); var CustomSceneConfig = Object.assign({}, BaseConfig, { springTension: 100, springFriction: 1, gestures: { pop: CustomLeftToRightGesture, } }); var Page1 = React.createClass({ _goToPage2() { AsyncStorage.setItem(STORAGE_KEY, "this is the key"); this.props.navigator.push({id: 2}) }, render() { return ( <View style={[styles.container, {backgroundColor: 'white'}]}> <Text style={styles.welcome}> This is Page 1 </Text> <TouchableOpacity onPress={this._goToPage2}> <View style={{paddingVertical: 2, paddingHorizontal: 7, backgroundColor: 'black'}}> <Text style={styles.buttonText}>Save Key</Text> </View> </TouchableOpacity> </View> ) }, }); var Page2 = React.createClass({ componentDidMount() { this._loadInitialState(); }, async _loadInitialState() { try { var value = await AsyncStorage.getItem(STORAGE_KEY); if (value !== null){ this.setState({selectedValue: value}) } else { } } catch (error) { } }, getInitialState() { return { selectedValue: null }; }, _signOutPressed(){ AsyncStorage.removeItem(STORAGE_KEY); this.props.navigator.push({id: 1}) }, render() { if(this.state.selectedValue === null) { begin = <Page1 /> } else{ begin = <View style={[styles.container, {backgroundColor: 'white'}]}> <Text style={styles.welcome}>This is Page 2</Text> <Text>KEY: {this.state.selectedValue}</Text> <TouchableOpacity onPress={this._signOutPressed}> <View style={{paddingVertical: 2, paddingHorizontal: 7, margin: 10, backgroundColor: 'black'}}> <Text style={styles.buttonText}>Delete Key</Text> </View> </TouchableOpacity> </View> } return ( begin ); }, }); var TestAsync = React.createClass({ _renderScene(route, navigator) { if (route.id === 1) { return <Page1 navigator={navigator} /> } else if (route.id === 2) { return <Page2 navigator={navigator} /> } }, _renderScene1(route, navigator) { if (route.id === 1) { return <Page1 navigator={navigator} /> } else if (route.id === 2) { return <Page2 navigator={navigator} /> } }, _configureScene(route) { return CustomSceneConfig; }, render() { var initialRoute = {id:1} if(AsyncStorage.getItem(STORAGE_KEY) != null){ initialRoute = {id:2} } return( <Navigator initialRoute={initialRoute} renderScene={this._renderScene} configureScene={this._configureScene} /> ); } }); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, color: 'black', }, buttonText: { fontSize: 14, textAlign: 'center', margin: 10, color: 'white', }, default: { height: 26, borderWidth: 0.5, fontSize: 13, padding: 4, marginHorizontal:30, marginBottom:10, }, }); module.exports = TestAsync;

You can do something like this, In TestAsync class你可以做这样的事情,在 TestAsync 类中

render() {
    var initialRoute = {id:1}
    if(AsyncStorage.getItem(STORAGE_KEY) != null){
       initialRoute = {id:2}
    }
    return(
       <Navigator
        initialRoute={initialRoute}
        renderScene={this._renderScene}
        configureScene={this._configureScene} />
    );
}

For 'Cannot read property push of undefined' error对于“无法读取未定义的属性推送”错误

In your page2 code in render method you need to pass reference of navigator在渲染方法中的 page2 代码中,您需要传递导航器的引用

Instead of而不是

 if(this.state.selectedValue === null) {
      begin = <Page1} />
 }

use this用这个

 if(this.state.selectedValue === null) {
      begin = <Page1 navigator={this.props.navigator} />
 }

If Anyone use React Navigation version 5 then,如果有人使用 React Navigation version 5那么

Check the following code.检查以下代码。 It may help它可能有帮助

function MyStack() {
  const [isLogedin, setIsLogedin] = React.useState(false);

  AsyncStorage.getItem('isLogedin').then((data) =>{
    if(data != null && data == true) setIsLogedin(true)
    else setIsLogedin(false)
  })

  return (
    <Stack.Navigator headerMode={"none"}>
      {isLogedin ? <Stack.Screen name="Home" component={AppTabs} /> : <Stack.Screen name="AuthNav" component={AuthNav} />}
    </Stack.Navigator>
  );
}

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

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