2017-05-09 20 views
0

我有MyFunction()填充我的渲染的listView的数据源,并且该进程在本地数据库上运行,并从屏幕的构造函数开始。试图呈现“加载”提示,但数据一旦准备就绪

构造:

constructor(props) { 
    super(props); 
    let MyDataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); 
    let MyData = MyFunction(); 
    let MyDataSource = MyDataSource.cloneWithRows(MyData); 

    this.state = { 
     Data: MyData, 
     DataSource: MyDataSource,}; 
} 

// .. 

render() { 
    return ( 
      <View> 
       <ListView 
        dataSource={this.state.dataSource} 
        renderRow={this.renderRow.bind(this)} 
        // .. 
       /> 
      </View> 
    ); 
} 

现在,我想MyFunction()远程数据库检索数据,因此它是将之前的数据已经准备好了一段时间服用。

我想在屏幕上显示“加载”消息,然后在数据准备就绪时更新屏幕。我修改我的代码如下:

constructor(props) { 
    super(props); 
    let MyDataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); 
    let MyData = MyFunction(); // this is an async now, and will take sometime to finish 
    let MyDataSource = MyDataSource.cloneWithRows(MyData); 

    this.state = { 
     Data: MyData, 
     DataSource: MyDataSource, 
     IsLoading: true, // so I added this 
    }; 
} 

// .. 

async MyFunction() { 

    // .. 

    // this is what takes time now, and returns a promise, I use .then to set the final data 
    // it is an async method that has a "await fetch()" inside it 
    let dataFromServer = await getDataFromServer().then((response) => this.setState({isLoading: false, Data: response})); 

    // .. 
}  

render() { 
      if(this.state.isLoading) 
      { 
       return(
       <View style={styles.emptyListContainer}> 
        <Text style={styles.emptyListMessage}> 
         Loading Data ... 
        </Text> 
       </View> 
       ) 
      } 
      return ( 
        <View> 
         <ListView 
          dataSource={this.state.dataSource} 
          renderRow={this.renderRow.bind(this)} 
          // .. 
         /> 
        </View> 
      ); 
} 

但是,这呈现“加载..”然后为空。原因是.then之后的代码正在执行之前.then完成(我猜?)

我有点困惑如何实现这一点,因为我是新的反应原生和js。请和谢谢

回答

1

首先,你不需要数据的状态,因为你根本不使用它。

解决你的问题,你可以使用这样的构造:

constructor(props) { 
 
    super(props); 
 
    
 
    getDataFromServer().then((response) => { 
 
    let DataSource = new ListView.DataSource({ 
 
     rowHasChanged: (r1, r2) => r1 !== r2 
 
    }); 
 
    
 
    this.setState({ 
 
     IsLoading: false, 
 
     DataSource: DataSource.cloneWithRows(response) 
 
    }); 
 
    }); 
 

 
    this.state = { 
 
    IsLoading: true 
 
    }; 
 
}

相关问题