【问题标题】:How to show Loading on Button press POST request in React Native?如何在 React Native 中显示加载按钮按下 POST 请求?
【发布时间】:2019-03-20 15:05:06
【问题描述】:

我正在我的 React Native 项目中创建一个注册页面。在此页面中,当用户按下注册按钮填写表单后,将调用一个 POST 请求。虽然 POST 请求响应需要一些时间,但我想在我的屏幕上显示 Loading,直到我收到来自服务器的任何响应。

这是我的代码-

    import React from 'react';
    import { StyleSheet, Text, View, ScrollView,  TextInput,
  Button,
  TouchableHighlight,
  Image,
  Alert, ActivityIndicator } from 'react-native';

class WelcomeScreen extends React.Component {

  constructor() {
    super();
    this.state = {
      first_name:'',
      last_name:'',
      email   : '',
      mobile: '',
      password:'',
      confirmPassword:'',
      showLoader:false
    }
  };


  showLoader = () => { this.setState({ showLoader:true }); };
  hideLoader = () => { this.setState({ showLoader:false }); };

 doSignup(){
   this.showLoader();
 }

  updateValue(text, field) {
    if(field == 'first_name') {
      this.setState({
        first_name: text
      })
    }
    else if(field == 'last_name') {
      this.setState({
        last_name : text
      })
    }

    else if(field == 'email') {
      this.setState({
        email : text
      })
    }

    else if(field == 'mobile') {
      this.setState({
        mobile : text
      })
    }

    else if(field == 'password') {
      this.setState({
        password : text
      })
    }

    else if(field == 'confirmPassword') {
      this.setState({
        confirmPassword : text
      })
    }


  }

  onClickListener = (viewId) => {
    Alert.alert("Alert", "Button pressed "+viewId);
  }



  submit() {
    let collection = {}

    collection.first_name = this.state.first_name,
    collection.last_name = this.state.last_name,
    collection.email = this.state.email,
    collection.mobile = this.state.mobile
    collection.password = this.state.password,



    console.log('#HELLO:', collection);

    var url = 'my url';

    if(collection.first_name != '' && collection.last_name != '' &&
    collection.email != '' && collection.mobile != '' &&
    collection.password != '') {

      if(this.state.password === this.state.confirmPassword) {


        fetch(url, {
          method: 'POST',
          body: JSON.stringify(collection),
          headers: new Headers({
            'Content-Type' : 'application/json',
            'token': 'token'
          })
        }).then(res => res.json())
        .catch(error=> console.error('Error:', error))
        .then(response => console.log('Success:', response));

      } else {
        Alert.alert('Password and Confirm Password didn\'t match');
      }


    } else {
      Alert.alert('Please fill up the required field');
    }




  }



  render() {
    return (

      <ScrollView keyboardShouldPersistTaps={'handled'}>

      <View style={styles.container}>
        <View style={styles.inputContainerEmail}>
          <Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}/>
          <TextInput style={styles.inputs}
              placeholder="Email"
              keyboardType="email-address"
              underlineColorAndroid='transparent'
              onChangeText={(text) => this.updateValue(text, 'email')}/>
        </View>

        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
          <TextInput style={styles.inputs}
              placeholder="Password"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(text) => this.updateValue(text, 'password')}/>
        </View>

        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
          <TextInput style={styles.inputs}
              placeholder="Confirm Password"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(text) => this.updateValue(text, 'confirmPassword')}/>
        </View>

        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/administrator-male.png'}}/>
          <TextInput style={styles.inputs}
              placeholder="First Name"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(text) => this.updateValue(text, 'first_name')}/>
        </View>


        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/administrator-male.png'}}/>
          <TextInput style={styles.inputs}
              placeholder="Last Name"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(text) => this.updateValue(text, 'last_name')}/>
        </View>


        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/phone.png'}}/>
          <TextInput style={styles.inputs}
              placeholder="Phone No."
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              textContentType='telephoneNumber'
              onChangeText={(text) => this.updateValue(text, 'mobile')}/>
        </View>

        <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress=
        {()=>{this.submit(); this.doSignup;}}>
          <Text style={styles.loginText}>Register</Text>
        </TouchableHighlight>

        <TouchableHighlight style={styles.buttonContainer} onPress={() => this.onClickListener('restore_password')}>
            <Text>Forgot your password?</Text>
        </TouchableHighlight>

        <TouchableHighlight style={styles.buttonContainerRegister} onPress={() => this.onClickListener('register')}>
            <Text>Sign In</Text>
        </TouchableHighlight>
      </View>


      <View style={{ position: 'absolute', top:"50%",right: 0, left: 0 }}>
      <ActivityIndicator animating={this.state.showLoader} size="large" color="red" />
    </View>

      </ScrollView>
    );
  }
}

我尝试了以下解决方案-

Show loader when button is clicked in react native

但它们都不适用于我的情况。我不明白为什么在按下注册按钮后加载没有显示,因为响应需要一些时间。因此,如果有人帮助找到问题并提供解决问题的建议,那就太好了。

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您将加载视图放置在 ScrollView 内,这可能会打乱定位。最好将 ScrollView 包装在包含 View 中,并将加载 View 作为 ScrollView 的兄弟,使用条件渲染显示它。

    render() {
        return <View style={{flex: 1}}>
            <ScrollView style={{flex: 1}}>
                {/* contents here */}
            </ScrollView>
            {
                this.state.showLoader && <View style={{ position: 'absolute', top:"50%",right: 0, left: 0 }}>
                    <ActivityIndicator size="large" color="red" />
                </View>
            }
        </View>;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 2020-05-15
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2015-07-04
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多