【发布时间】:2017-05-09 19:36:20
【问题描述】:
我有 MyFunction() 为我的渲染列表视图填充数据源,该过程在本地数据库上运行并在屏幕的构造函数中启动。
构造函数:
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。请和谢谢
【问题讨论】:
标签: javascript reactjs asynchronous react-native promise