ActivityIndi​​cator 在本机反应中不起作用

ActivityIndicator not working in react native

我正在与 react-native-push-notification 合作。单击按钮时,我想删除之前创建的本地通知,我可以使用 PushNotification.cancelLocalNotifications({id: '123'}) 来完成。我想在删除通知时显示 activity 指示器,但我遇到了问题。

这是我的代码。单击按钮时触发此方法:

import React from 'react';
import {
    View,
    Text,
    Button,
    ActivityIndicator,
} from 'react-native';
import PushNotification from 'react-native-push-notification';

export default class App extends React.Component {

    constructor() {
        super();
        this.state = {
            spinner: false,
        }
    }

    delete = (id) => {
        this.setState({ spinner: true });
        var userid = id;
        var temp = 0;
        //I want to start my activity Indicator here
        for (let i = 0; i < 50; i++) {
            temp = Number(userid) + Number(i);
            PushNotification.cancelLocalNotifications({
                id: temp,
            });
        }
        this.setState({ spinner: false });
        // I want to stop my activity Indicator here
    }

    render() {

        if (this.state.spinner) {

            return (
                <View style={{ flex: 1, justifyContent: 'center' }}>
                    <ActivityIndicator/>
                </View>
            );
        } else {
            return (
                <View>
                    //code snippet
                    <TouchableOpacity onPress={() => this.delete(id)}>
                        <Text>click</Text>
                    </TouchableOpacity>
                </View>);
        }
    }
}

看来cancelLocalNotifications方法只是依次调用了一个Native Bridge方法,doesn't return anything.

这意味着你不知道函数什么时候完成。

我的建议是伪造调用,让应用看起来像是做了一些工作。

按照这些思路应该没问题:

delete = (id) => {
  this.setState({ spinner: true });

  // ...

  // Wait 2 seconds and then hide the spinner
  setTimeout(() => {
    this.setState({ spinner: false });
  }, 2000);
}

这里的删除函数是异步的,所以,for-loop可能会在this.setState({ spinner: true });

之前开始

this.setState({ spinner: false });可能会在this.setState({ spinner: true });之后立即运行,而for-loop保持运行宁。

您可以在 for-loop 中设置微调器变量:

delete = (id) => {
        var userid = id;
        var temp = 0;
        for (let i = 0; i < 50; i++) {
            if (i == 0) {
                //start indicator here
                this.setState({ spinner: true });
            }
            temp = Number(userid) + Number(i);
            PushNotification.cancelLocalNotifications({
                id: temp,
            });
            if (i == 49) {
                //end indicator here
                this.setState({ spinner: false });
            }
        }
    }