Javascript 试图呈现一个;“装载”;提示,但一旦数据准备就绪,就立即删除数据

Javascript 试图呈现一个;“装载”;提示,但一旦数据准备就绪,就立即删除数据,javascript,reactjs,asynchronous,react-native,promise,Javascript,Reactjs,Asynchronous,React Native,Promise,我有一个MyFunction(),它为渲染的listView填充数据源,该过程在本地数据库上运行,并在屏幕的构造函数中启动 建造商: constructor(props) { super(props); let MyDataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); let MyData = MyFunction(); let MyDataSource

我有一个
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>
     ); 
}  
但这会使“加载…”变为空。原因是
之后的代码。然后
之前执行。然后
完成了(我想是吧?)


对于如何实现这一点,我有点困惑,因为我是一个新手,不熟悉如何使用native和js。首先,您不需要状态中的数据,因为您根本不使用它

要解决您的问题,您可以使用以下构造函数:

构造函数(道具){
超级(道具);
getDataFromServer()。然后((响应)=>{
让DataSource=新建ListView.DataSource({
行已更改:(r1,r2)=>r1!==r2
});
这是我的国家({
孤岛加载:false,
DataSource:DataSource.cloneWithRows(响应)
});
});
此.state={
孤岛加载:正确
};
}
 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>
            ); 
}