【问题标题】:How to show loading icon in react native until the API response in react native?如何在反应原生中显示加载图标,直到反应原生的API响应?
【发布时间】:2019-10-30 02:06:52
【问题描述】:

我正在创建一个新应用。点击提交按钮后,我想在登录页面中显示加载图标,直到 API 响应。请帮帮我

【问题讨论】:

    标签: react-native


    【解决方案1】:

    首先创建一个用于显示和隐藏loader的状态变量,如下所示

    this.state = {
    ..
    loading: false, 
    ..
    };
    

    在请求发送前的api调用中,可以设置loading状态为true,完成响应后设置为false

    getData() {
    
      this.setState({loading:true});// For showing loader
      axios.get('api_link_goes_here')
      .then(response => {
        this.setState({loading:false});// For hiding loader
        console.log(response.data);
      })
      .catch(error => {
        this.setState({loading:false});// For hiding loader
        console.log(error);
      });
    }
    

    在您的渲染模板中,您可以添加一个基于状态显示加载器的视图,您可以将其添加到底部和位置并使其全屏以避免进一步点击,直到收到响应

    render() {
        return (
    <View style={container}> 
    .....
    
    {this.state.loading === true &&
      <View style={styles.myloader}>
        <CustomLoader /> // You can define this in another component or simply write <Text>Please wait...</Text>
      </View>
    }
    
    ....
    </View> 
    )}
    

    下面给出了加载器容器的样式

    const styles = StyleSheet.create({
    .....
    
        myloader: {
            position: "absolute",
            top: 0,
            left: 0,
            zIndex: 10,
            backgroundColor: "#ffffff",
            opacity: 0.9,
            justifyContent: 'center',
            alignItems: 'center',
            width: "100%",
            height: "100%"
        }
    
    ...
    });
    

    【讨论】:

    • 你可以尝试不同的变化,这取决于你的设计,上面的代码是我在一个项目中使用的自定义方法。如果可以,请尝试不同的...一切顺利:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2018-12-09
    • 2019-05-21
    • 2022-07-05
    相关资源
    最近更新 更多