计算数据时渲染ActivityIndi​​cator

时间:2018-09-27 18:31:09

标签: react-native

我正在编写某种计算器,但是在处理数据时呈现ActivityIndi​​cator时遇到问题。

 class Calculator extends Component {
     constructor(props) {
         super(props);

         this.state = {
            ... //input fields state
            isLoadingVisible: false,
            renderData: true
          }
          this.calculationResult = null;
          ... //some bindings
        }

      handleCalculateButtonPressed = () => {
         this.setState({isLoadingVisible: true});

         ... //some calculations and creating of new components
         this.calculationResult = <Result ... //some props with calculated data />
         this.setState({renderData: !this.state.renderData, isLoadingVisible: false});
      }

render() {
        let indicator = (this.state.isLoadingVisible) ? <ActivityIndicator size = "large" /> : null;

        return (
            <ScrollView>
                <View>
                 ... //input fields and some text data
                 <Button title = ... onPress = 
                {this.handleCalculateButtonPressed}></Button>
                    </View>
                <View>
                    {indicator}
                    {this.calculationResult}
                </View>
                </ScrollView>

    }

我要在按下“计算”按钮后呈现活动指示器,并在完成计算后将其从屏幕上删除。但是当前活动指示器从未呈现。我认为这个问题与所有js代码都在一个线程中运行这一事实有关,因此我们需要先完成计算功能,然后才可以重新渲染屏幕,但实际上我不再需要它了。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, ActivityIndicator, Image,    ScrollView, Button } from 'react-native';

export default class App extends Component {
constructor(props) {
super(props);

this.state = {
  isLoadingVisible: false,
  result: 0
}
}

handleCalculateButtonPressed = () => {
this.setState({ isLoadingVisible: true });

setTimeout(()=>{
  this.setState({ isLoadingVisible: false, result: 10 });
},2000)
}

render() {
return (
  <ScrollView>
    <View>
      <Button title="here" onPress={this.handleCalculateButtonPressed}></Button>
    </View>
    {
      this.state.isLoadingVisible ? <ActivityIndicator size="large" /> : <View>
      <Text>{this.state.result}</Text>
    </View>
    }
  </ScrollView>

)
}
}

我设置超时只是为了表明加载正在工作