0

buenos dias soy nuevo en react native y tengo 2 ventanas y entonces una es el login y la otra muestra una lista de objetos entonce quiero saber como hago para llevarme el nombre con el que hice sesion a la otra ventana y mostrarlo en un < Text >

VENTANA DE LOGIN --- /pages/loginView

import React from 'react';
import {StyleSheet,Text,Dimensions,View,TouchableOpacity,TextInput,Keyboard,Image,Alert} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

const {width, height} = Dimensions.get('window');

export default class loginView extends React.Component {
  static navigationOptions= ({navigation}) =>({title: 'Login'});  

  constructor(props){
    super(props)
    this.state={userName:'', userPassword:'', }
  }

  login=()=>{
    const {userName,userPassword} = this.state;

    if(userName=="" || userPassword==""){this.setState({mensaje:'debe llenar los campos'})}
    else{
      fetch('http://www.yarascorp.com/reactnative/login.php',{
        method:'post',
        header:{'Accept':'application/json', 'Content-type':'application/json'},
        body:JSON.stringify({name:userName, password:userPassword })
      })
      .then((response)=>response.json())
      .then((responseJson)=>{
        if(responseJson == "Correcto"){
          this.setState({mensaje:'Inicio correcto'})
          this.props.navigation.navigate("Profile");
        }else{
          this.setState({mensaje:'Error con el usuario o clave'})
        }
      })
      .catch((error)=>{console.error(error);});
    }
    Keyboard.dismiss();
  }

  render() {
    return ( 
      <View style={styles.container}>    
        <View style={styles.contlogo}>
                    <View style={styles.hlogo}><Image style={styles.coverImage1} source={require('../imgs/costco.png')}/></View>
                    <View style={styles.hlogo}><Image style={styles.coverImage2} source={require('../imgs/logometalss.png')}/></View>
                </View>
        <View style={styles.cuerpo}>
          <View style={styles.campos}>
            <Icon style={styles.infoIcon} name="user" size={20} color="grey"/>
            <TextInput 
              placeholder="Ingrese Usuario" style={styles.textInput} underlineColorAndroid="transparent" 
              onChangeText={userName => this.setState({userName})} value={this.state.userName}
            />
          </View>
          <View style={styles.campos}>
            <Icon style={styles.infoIcon} name="key" size={20} color="grey"/>
            <TextInput 
              secureTextEntry={true} placeholder="Ingrese Clave" style={styles.textInput} 
              underlineColorAndroid="transparent" onChangeText={userPassword => this.setState({userPassword})} value={this.state.text1}/>
          </View>
          <TouchableOpacity onPress={this.login}style={{width:250,padding:10,marginTop:20,backgroundColor:"#A30000",alignItems:'center'}}>
            <Text style={{color:'white',fontWeight:'bold'}}>Entrar</Text>
          </TouchableOpacity>
          <Text style={styles.mensaje}>{this.state.mensaje}</Text>
        </View>
      </View>
    );
  }
}

VENTANA DE VISUALIZACION --- /pages/visorView

import React from 'react';
import {StyleSheet,Text,View,Button,Alert,ActivityIndicator,ListView,Platform,TouchableOpacity} from 'react-native';
import loginView from '../pages/loginView';


export default class visorView extends React.Component{
  static navigationOptions=({navigation}) =>({header: null,}); 
  static navigationOptions={tabBarLabel:'Visor'}


  constructor(props){
    super(props);
    this.state={
      isLoading: true,
    }
  }

  GetItem (cliente,deservicios){
    Alert.alert(cliente, deservicios);
  }

  componentDidMount(){
    return fetch('http://www.yarascorp.com/reactnative/ordenesprcostco.php')
    .then((response)=>response.json())
    .then((responseJson)=>{
      let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.setState({
        isLoading: false,
        dataSource: ds.cloneWithRows(responseJson),
      },function(){
        // In this block you can do something with new state.
      });
    })
    .catch((error)=>{
      console.error(error);
    });
  }

  ListViewItemSeparator=()=>{
    return(
      <View
        style={{
          height:.5,
          width:"100%",
          backgroundColor:"#000",
        }}
      />
    );
  }

  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }
    return(
      <View style={styles.container}>
        <View style={styles.cabecera}>
          <Text style={styles.titulo}>- Visor de pedidos -</Text> 
        </View>
        <View style={styles.MainContainer}>
          <ListView
            dataSource={this.state.dataSource}
            renderSeparator={this.ListViewItemSeparator}
            renderRow={(rowData) =>
              <View style={{flex:1, flexDirection: 'column'}} >
                <TouchableOpacity onPress={this.GetItem.bind(this,rowData.cliente,rowData.descripcion)} >
                <Text style={styles.textViewContainer} autoCapitalize="characters">{rowData.cliente+' / '+rowData.direccion}</Text>
                </TouchableOpacity>
              </View>
            }
          />
        </View>
      </View>
    );
  }
}
1
  • Me preocupa que usted es nuevo con React-Native y espero escribir tanto codigo antes de pedir ayuda. Debugging y testing son la fundacion de programar. Disculpe mi teclado esta en ingles.
    – Daniel
    el 28 oct. 2018 a las 21:33

3 respuestas 3

1

Tienes varias formas de hacerlo, una de ellas es utilizar Redux, que te permite tener estados globales y poder acceder a ellos desde cualquier punto de tu aplicación.

Otra y en este caso la más sencilla para ti, es utilizando las propias opciones de React Navigation.

La manera de hacerlo con React Navigation es muy sencilla.

Primero tienes que enviar estos atributos al redirigir a otra pantalla:

 this.props.navigation.navigate("Profile", {tuAtributo: userName});

Luego en la siguiente pantalla puedes acceder a él de la siguiente manera:

 this.props.navigation.getParam(tuAtributo);

Te dejo aquí la referencia: https://reactnavigation.org/docs/en/params.html

0

También puedes optar por usar AsyncStorage de React Native, para usar ese nombre en varias ocaciones y en todos lados sin tener que pasarlo por propiedades a cada vista

AsyncStorage.setItem('nombre', 'Juan');

Y para poder usarlo en otras vistas seria

AsyncStorage.getItem('nombre');

No se te olvide importarlo

import { AsyncStorage } from 'react-native';
0

Tal y como te comenta Gusy, en tu caso podrías reenviar el nombre de usuario con navigation de la siguiente forma:

login=()=>{
    const {userName,userPassword} = this.state;

    if(userName=="" || userPassword==""){this.setState({mensaje:'debe llenar los campos'})}
    else{
      fetch('http://www.yarascorp.com/reactnative/login.php',{
        method:'post',
        header:{'Accept':'application/json', 'Content-type':'application/json'},
        body:JSON.stringify({name:userName, password:userPassword })
      })
      .then((response)=>response.json())
      .then((responseJson)=>{
        if(responseJson == "Correcto"){
          this.setState({mensaje:'Inicio correcto'}) // Esta línea no tiene sentido sí cambias de screen
          //
          this.props.navigation.navigate("Profile",{
              username=userName, 
          });
          //
        }else{
          this.setState({mensaje:'Error con el usuario o clave'})
        }
      })
      .catch((error)=>{console.error(error);});
    }
    Keyboard.dismiss();
  }

Y en la 'Ventana de Visualización':

export default class visorView extends React.Component{

   static navigationOptions=({navigation}) =>({header: null,}); 
   static navigationOptions={tabBarLabel:'Visor'}

   //
   static username=this.props.navigation.getParam('username');

   ....
}

Pero posiblemente necesites usar esta y otra variables de sesión en diferentes secciones de la aplicación y te será necesario y/o útil hacer uso de AsyncStorage o Redux.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.