work with props and states react native

0

good morning I'm new to react native and I have 2 windows and then one is the login and the other shows a list of objects then I want to know how I do to take the name with which I made the session to the other window and display it in a < Text >

LOGIN WINDOW --- / 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>
    );
  }
}

VISUALIZATION WINDOW --- / 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>
    );
  }
}
    
asked by Damian bohorquez 26.09.2018 в 17:20
source

2 answers

0

You have several ways of doing it, one of them is to use Redux, which allows you to have global states and be able to access them from any point of your application.

Another and in this case the simplest for you, is using React Navigation's own options.

The way to do it with React Navigation is very simple.

First you have to send these attributes to redirect to another screen:

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

Then on the next screen you can access it as follows:

 this.props.navigation.getParam(tuAtributo);

I leave here the reference: link

    
answered by 10.10.2018 в 17:38
0

You can also choose to use React Native's AsyncStorage, to use that name several times and everywhere without having to pass it through properties at every view.

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

And to be able to use it in other views, it would be

AsyncStorage.getItem('nombre');

Do not forget to import it

import { AsyncStorage } from 'react-native';
    
answered by 15.11.2018 в 16:49