javascript - 如何在 React Native 中显示按按钮按下 POST 请求时正在加载?

标签 javascript react-native

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

这是我的代码-

    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

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

最佳答案

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

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>;
}

关于javascript - 如何在 React Native 中显示按按钮按下 POST 请求时正在加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55264019/

相关文章:

reactjs - React JS Web 代码可以用于使用 React Native 构建移动应用程序吗?

javascript - require ('react-native' ).NativeModules 是一个空对象

android - 生成 APK 后 react native 黑屏

xcode - 未找到调试 iphonesimulator/YogaKit/YogaKit.modulemap'

javascript - package.json "latest"版本是否包含测试版?

javascript - winston 记录器不写入文件

javascript - getElementById 和 null - 为什么?

javascript - React Native 图像不可见

javascript - 在 Angular JS 中根据 Controller 逻辑创建服务

JavaScript 展开/折叠更改图像