首页 > 解决方案 > react-native 中的小问题 活动指标 | 组件 | 组件内的道具 | 道具 | 设置状态

问题描述

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

这是代码:

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}));
  }

但它没有用

所以任何想法!!!!????

标签: functionreact-nativecomponentsstateactivity-indicator

解决方案


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

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

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} />
         />
  ))}
}

在此处查找 forcomponentWillMount和其他生命周期方法的用法


推荐阅读