React-Native的ActivityIndicator在动画结束后无法隐藏。

7

我有一个ActivityIndicator,在加载信息时显示转动的菊花图标,当componentDidMount被触发时,该图标会消失,但在页面布局中仍会保留一个空块。我猜想如何卸载这个组件,但是我尝试的所有方法都没有效果。

我目前使用的版本是:

react-native-cli: 2.0.1
react-native: 0.40.0

这是我使用的代码的一部分:
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  ... // Couple more components here
  ActivityIndicator,
} from 'react-native';

import NewsList from './NewsList';

export default class HomeView extends Component {

  constructor(props) {
     super(props);
     this.state = {
       noticias: [],
       animating: true,
     };
   }

componentDidMount(){
    fetchFunction() // My fetch function here
      .then(data => this.setState({ data:data }))
      this.state.animating = false
  }

render() {

    return (
        <View>
            <NewsList data={data} /> // My custom component

            <ActivityIndicator
            animating={this.state.animating}
            style={[{height: 80}]}
            color="#C00"
            size="large"
            hidesWhenStopped={true}
            />
        </View>
    );

  }
}

PS:我没有使用Redux。

ActivityIndicator和动画一起正常工作 当动画设置为false时,会出现空白的区域


为什么你没有像前一行那样使用setState,而是写成了this.state.animating = false? - RRikesh
我改成了: .then(data => this.setState({ data:data, animating: false })) 并且得到了相同的结果。 - vtisnado
2个回答

22

我建议你阅读更多关于JSX的内容,以便学习如何有条件地显示内容。https://facebook.github.io/react/docs/jsx-in-depth.html

当我们不需要加载任何内容时,我会完全将ActivityIndicator从DOM中移除。

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

import NewsList from './NewsList';

export default class HomeView extends Component {
  state = {
    data: [],
    isLoading: true,
  }

  componentDidMount() {
    fetchFunction()
      .then(data => this.setState({ data, isLoading: false }))
  }

  render() {
    const {data, isLoading} = this.state;

    return (
      <View>
        <NewsList data={data} />
        {isLoading && (
          <ActivityIndicator
            style={{ height: 80 }}
            color="#C00"
            size="large"
          />
        )}
      </View>
    );
  }
}

谢谢!这对我很有帮助。我会查看JSX文档。 现在一切都按预期工作 :) - vtisnado
如果一切正常,请将此答案标记为正确,以便其他人轻松找到它 :) - Henrik R

4

如果您想让组件重新渲染,您应该使用setState。

this.setState({ animating: false })

而不是

this.state.animating = false

我忘了提到我是React的新手(大约一周左右),所以我没有注意到那行代码中的错误。感谢您抽出时间提醒我,现在我已经修复了它,但是“空白”空间仍然存在 :( - vtisnado

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接