首页 > 解决方案 > 更改屏幕时没有出现 ActivityIndi​​cator

问题描述

我有一个列表视图,其中有 45 个项目要加载图像。我希望当您转到此页面时,加载过程中会出现加载。

但是负载没有出现。屏幕在显示视图前冻结 2 秒

我将 React Navigation 与 TabNavigator 一起使用。在菜单中,一个按钮通向这个视图。

我试图设置一个 setState 但它不起作用。

我的代码:

class Exhibitors extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true
        }
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.setState({isLoading: false});
        });
    }

    render() {
        if (this.state.isLoading) {
            return this._displayLoading(); // Simple Activity Indicator
        }
        // My List
    }

    _displayLoading() {
        return (
            <View>
                <ActivityIndicator size='large' />
            </View>
        )
    }
}

我的印象是我的应用程序在显示负载之前加载了视图。

目前,当我单击菜单按钮时,屏幕会在显示带有列表的视图之前冻结。

我现在希望,只要我单击菜单,新视图就会随着加载打开。

标签: react-native

解决方案


试试三元运算符。

用法

class Exhibitors extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true
        }
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.setState({isLoading: false});
        });
    }

      render() {
    return (
    this.state.isLoading === true ?  (
      <View style={{flex:1,justifyContent: 'center',alignItems:"center"}}>
        <ActivityIndicator size="large" color="#0000ff" />
        <ActivityIndicator size="small" color="#00ff00" />
      </View>
    )
    :
     (
      <View ...
     )
    );
  }
}

例子

import React, { Component } from 'react'
import {
  ActivityIndicator,
  StyleSheet,
  Text,
  View,
} from 'react-native'

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state={
      loading: false
    }
  }

  componentDidMount() {
    this.setState(state => ({
  ...state,
  loading: true 
}));
  }
  render() {
    return (
    this.state.loading === false ?  (
      <View style={[styles.container, styles.horizontal]}>
        <ActivityIndicator size="large" color="#0000ff" />
        <ActivityIndicator size="small" color="#00ff00" />
      </View>
    )
    :
     (
      <View style={[styles.container, styles.horizontal]}>
       <Text>ActivityIndicator</Text>
      </View>
     )
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center'
  },
  horizontal: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 10
  }
})

推荐阅读