【问题标题】:React-Native ActivityIndicator doesn't hide after animation finish动画完成后 React-Native ActivityIndi​​cator 不隐藏
【发布时间】:2017-06-10 03:22:17
【问题描述】:

我有一个 ActivityIndi​​cator,它在 fetch 加载时显示,当 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 with animation working fine The empty space when animating is set to false

【问题讨论】:

  • this.state.animating = false 为什么不像上一行那样使用 setState?
  • 我改成:.then(data =&gt; this.setState({ data:data, animating: false })) 得到了同样的结果

标签: javascript react-native jsx uiactivityindicatorview activity-indicator


【解决方案1】:

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

当我们不加载任何内容时,我会从 DOM 中完全删除 ActivityIndicator

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 文档。现在按预期工作:)
  • 如果一切正常,请将此答案标记为正确,以便其他人轻松找到:)
【解决方案2】:

如果你想再次渲染你的组件,你应该使用 setState。

this.setState({ animating: false })

而不是

this.state.animating = false

【讨论】:

  • 我忘了提到我是 React 的新手(大概一周左右),所以我没有注意到那一行的错误。感谢您花时间提及它,现在我修复它但“空白”空间仍然存在:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
相关资源
最近更新 更多