Navigator & AsyncStorage react native

3

你好,我是一名新手,在学习关于AsyncStorage的React Native技术。我想要实现一个条件渲染导航器。如果在AsyncStorage中有value键,则初始路由将转到Page2;如果在AsyncStorage中没有value键,则初始路由将转到Page1。

如果我关闭应用程序并重新打开它,我希望它能显示与key是否存在相应的页面。请帮助我。

目前为止,我已经完成的工作如下:

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;

2个回答

3
你可以这样做,在 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} />
    );
}

针对“Cannot read property push of undefined”错误

在你的page2代码的render方法中,你需要传递导航器的引用。

而不是

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

使用这个

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

已解决!非常感谢@abhishek。 - user6487402
哦等等,在Page1页面中,当我点击“保存键”按钮时,它显示错误“无法读取未定义的push属性”。有什么解决办法吗? - user6487402
可能您的导航器引用未在属性中设置。您能否更新您的代码? - Abhishek

2
如果有人使用React Navigation的版本5,那么可以检查下面的代码。这可能会有所帮助。
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>
  );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接