【问题标题】:small issue in react-native | ActivityIndicator | component | props inside a component | props | setStatereact-native 中的小问题活动指标 |组件 |组件内的道具 |道具 |设置状态
【发布时间】:2019-10-30 14:12:27
【问题描述】:

所以我的问题是我需要在函数/组件中设置一个状态。 默认情况下,状态“isLoading”设置为 true (用于 ActivityIndi​​cator ),我需要在组件内将其更改回 false 以便 indicator 停止工作,组件呈现结果。

代码如下:

const Data = require('../data/my_data.json');

export default class Albums extends React.Component {

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

componentWillMount() {
    return this.state.Data_list.map(something=> (
      <list_Detail key={something.id} something={something} />
    ));
  }

render() {
    if(this.state.isLoading){
       return(
        <View style={{flex: 1, padding: 20}}>
           <ActivityIndicator/>
        </View>
       )
    }
return (
    <ScrollView>{this.componentWillMount()}</ScrollView>

    )}
}

我已经试过了:

componentWillMount() {
    return this.state.Data_list.map(something=> (
      <list_Detail key={something.id} something={something} />
    ))
    .then(this.setState({isLoading: false}));
  }

但是没用

任何想法!!!!????

【问题讨论】:

  • 为什么要使用指标从本地文件导入数据?
  • 我使用了指标,因为导入数据需要时间(比如 3 秒),所以在这 3 秒内我需要显示指标,以便用户知道正在加载某些内容,他只需要等待它。现在在state isLoading 设置为 true 所以指标可以显示在屏幕上,但在导入所有数据后我需要将其设置回 false跨度>
  • @hongdevelop 我正在编辑我的帖子,以便您了解我到底在做什么

标签: function react-native components state activity-indicator


【解决方案1】:

componentWillMount 是一个生命周期方法,在组件渲染之前被调用。您不能从此方法返回 UI

将 UI 部分移至 render 方法并仅保留 componentWillMount 中的 api 调用。

componentWillMount() {
    axios.get('https://api.jsonbin.io/b/5d05c8712132b7426d0')
    .then(response => this.setState({Data: response.data, isLoading: false}));
    )); 
}

render方法中,

render(){
  return (
  //other UI
  {this.state.Data.map(something => (
          <list_Detail key={something.id} something={something} />
         />
  ))}
}

查找componentWillMount 和其他生命周期方法here 的用法

【讨论】:

  • 感谢您的回答并向我解释,但它按原样工作正常,但您没有回答我与女巫斗争的真正问题设置为@987654329 @ 在这个组件内部:componentWillMount() { return this.state.Data.map(something=&gt; ( &lt;list_Detail key={something.id} something={something} /&gt; )); }
  • 在 API 响应到达时已经将 isLoading 设置为 false,为什么还要设置它?
  • 我需要在第二个componentWillMount() 中将isLoading 设置为false没有 API 响应的那个。
  • 我正在编辑我的帖子,以便您了解我到底在做什么
猜你喜欢
  • 2017-05-16
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
  • 2015-07-24
  • 2020-05-04
  • 2021-09-15
相关资源
最近更新 更多