我有 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
完成之前执行(我猜?)
我对如何实现这一点有点困惑,因为我是 React Native 和 js 的新手。请并感谢
最佳答案
首先,您不需要状态数据,因为您根本不使用它。
要解决您的问题,您可以使用这样的构造函数:
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
};
}
关于javascript - 尝试呈现 "loading"提示,但数据一旦准备好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43878483/