如何加载渲染给出条件'如果'在React Native?

时间:2018-03-20 18:16:24

标签: react-native

我在Chrome浏览器中使用调试模式,在我的手机中使用iOS模拟器展示。在我的应用程序中,我想渲染,但这个渲染,取决于' X'值。

所以我有窗口1和窗口2,我想要:

  • 如果X = = null,则加载窗口1,窗口1转到窗口2
  • 如果X是!== null,则它直接加载到窗口2而不传递window1。

这是我的所有进口

import React, {Component} from 'react';
import {View, Text, Button, TextInput, Alert,ScrollView,AsyncStorage} from 
'react-native';
import axios from 'axios';

我的Css For my Component

const myStyle = {
principal: {
    paddingTop: 17,
    paddingLeft: 2,
    flex: 1,
    backgroundColor: 'black',
    justifyContent: 'center',
    alignItems: 'center',
},
caixa: {
    backgroundColor: 'white',
    height: 300,
    borderWidth: 1,
    width: 300,
    borderColor: 'black',
    alignItems: 'center',
    borderRadius: 20,
},
inputPin: {
    backgroundColor: 'white',
    width: 290,
    height: 40,
    borderRadius: 15,
    borderWidth: 1,
    borderColor: 'black',
    marginTop: 60,
    marginBottom: 30,
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: 20,
    //paddingLeft:20,
    color: 'black',
    textAlign: 'center'
},
bemVindo: {
    fontSize: 40,
    marginBottom: 20,
},
botao: {
    alignItems: 'center',
},
texto: {
    textAlign: 'center',
    fontSize: 20,
    color: 'black',
    backgroundColor: 'white',
   }
  }

我使用extends

声明了我的课程
let mgm = '!!Ups, Inseriu O Pin Errado, Insira O Correcto';

export default class PaginaInicial extends React.Component {
    constructor(props) {
        super(props);
        this.state = {isLoaded: true}
    }
    HttpRequest(){
    axios({
        method: 'post',
        url: 'https://api.feetit.com/shoestorebranch/auth?
 key=q59Sgv0sRr0i9Qh00aWM071hB76NZh9WcW4o3HPPpw847OT8T17Sq62n3O7FTT9n',
        data: {
            loginHash: this.state.codigoPin,
        }
    }
    ).then((response) => {
        //AsyncStorage.removeItem('localData', () => {});
        this.setState({dados: response.data.response})
        console.log('SUCCESS');

        if(this.state.dados.admin === null){
            Alert.alert('Loja sem Administrador atribuido, por favor 
          contacte o suporte.');
        }else{

            //console.log(this.state.dados);
            let tmp_localData = {};
            console.log("tmp_localData: ", tmp_localData);
            AsyncStorage.getItem('localData', (err, result) => {
                tmp_localData = result;

            }).then( (result) => {
                    if(tmp_localData == null) {
                        tmp_localData = {
                            "ShoeStoreBranch": null,
                            "User": null
                        }
                    }
                    if (!tmp_localData.hasOwnProperty("ShoeStoreBranch")) {
                        tmp_localData.ShoeStoreBranch = {};
                    }
                    tmp_localData.ShoeStoreBranch = {
                        "shoeStoreBranchID": 
           this.state.dados.shoeStoreBranchID,
                        "name": this.state.dados.name,
                        "ShoeStore": {
                            "shoeStoreID": 
           this.state.dados.shoeStore.shoeStoreID,
                            "name": this.state.dados.shoeStore.name
                        }
                    };
                    tmp_localData.User = {
                        "userID": this.state.dados.admin.userID,
                        "displayName": this.state.dados.admin.displayName,
                        "email": this.state.dados.admin.email,
                        "avatar": this.state.dados.admin.avatar,
                        "gender": this.state.dados.admin.gender,
                        "Session": {
                            "token": this.state.dados.admin.token
                        },
                        "FootID": this.state.dados.admin.FootID
                    }
                    AsyncStorage.setItem('localData', 
           JSON.stringify(tmp_localData), () => {});
                    this.props.navigator.push({id: 'MenuPrincipal'})
            });
            //var tmp_dados = this.getState()
            //var qqer =this.state.dados.admin.token;
            //console.log(JSON.stringify(qqer));
        }
    }).catch((error) => {
            if (error.response) {
                // The request was made and the server responded with a 
                 status code
                // that falls out of the range of 2xx
                console.log(error.response.data);
                console.log(error.response.status);
                console.log(error.response.headers);
                if(error.response.status === 403){
                    console.log('App não tem autorização',error.message);
                    Alert.alert('App não tem autorização');
                }else if(error.response.status === 404){
                    console.log('PIN inválido',error.message);
                    Alert.alert('PIN inválido');
                    AsyncStorage.getItem('localData', (err, result) => {
                        console.log(result);
                    });
                }else if(error.response.status >=400 && 
       error.response.status <500){
                    console.log('Erro, por favor contactar o 
       suporte',error.message);
                    Alert.alert('Erro, por favor contactar o suporte');
                }else{
                    console.log('Erro interno, por favor contactar o suporte',error.message);
                    Alert.alert('Erro interno, por favor contactar o suporte');
                }
            } else if (error.request) {
                // The request was made but no response was received
                // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
                // http.ClientRequest in node.js
                console.log('erro de ligaçao',error.message);
                Alert.alert('erro de ligaçao');
                console.log(error.request);
            } else {
                // Something happened in setting up the request that triggered an Error
                console.log('erro de codigo no then',error.message);
                Alert.alert('App error');
            }
            console.log(error.config);
            //console.log('Erro ao imprimir ao enviar os dados')
        });
}

componentDidMount() {
    AsyncStorage.getItem('localData').then((result) => {
        this.setState({
            isLoading: false
        });
    });
}

我使用的功能是这样的:

render(){
    if (this.state.isLoading) {
        if(result.hasOwnProperty("User") && result.User.hasOwnProperty("Session") && result.User.Session.hasOwnProperty("token") && (result.User.Session.token).length > 0) {
            console.log('USER JA LOGADO? -> SIM');
            return

如果state.isloading为false,我希望更改我的场景

            {this.props.navigator.push({id: 'MenuPrincipal'})};

        }
    }

这是when state.isLoading为真的时候

        const {principal, caixa, inputPin, bemVindo, botao, texto} = myStyle;
        return (
            <View style={principal}>
                <View style={caixa}>
                    <Text style={bemVindo}>Bem Vindo</Text>
                    <Text style={texto}>Para que possamos identificar-lhe, Indique a baixo o código pin</Text>
                    <TextInput placeholder='Código da Loja' style={inputPin}
                               onChangeText={(textoInput) => this.setState({codigoPin: textoInput})}
                    />
                    <Button title='Continuar'style={botao} onPress={() => {
                        this.HttpRequest();
                    }}
                    />
                </View>
            </View>
        );
    }
}

1 个答案:

答案 0 :(得分:2)

对于渲染基于条件的视图,您只需要在条件上返回视图。要理解这个例子,

export default class Home extends Component {
    constructor(props){
        super(props);
        this.state = {
           show = true
        }
     }

render(){
    if (this.state.show){
        return(
            <View>
                // this view visible when state.show is true
                <Text>Home is visible!</Text>
            </View>
        );
    } else if (!this.state.show){
        return(
            <View>
                // this view visible when state.show is false
                <Text>Home is not visible!</Text>
            </View>
        );
    }
  }
}