我需要從SQLite數據庫獲取數據,然後將其保存在組件狀態中。數據庫部分工作正常,問題是它不能很快保存到狀態。如果我用setTimeout添加一些人爲延遲,那麼它工作正常。我怎樣才能更好地將這些東西結合在一起,以便它們在沒有一百萬次回調的情況下以正確的順序和時序工作?等待異步數據在React或React Native中存儲狀態的正確方法
這不起作用:
let returnedData;
// This function works, the data comes back correctly eventually
returnedData = getDataFromDB();
this.setState({
dbData: returnedData //but returnedData is still empty at this point
})
// Data is not back in time to see in the variable or in state:
console.log(returnedData); // Undefined
console.log(this.state.dbData); // Undefined
但這並工作:
let returnedData;
returnedData = getDataFromDB();
// If I add this tiny delay, it all works
setTimeout(function(){
this.setState({
dbData: returnedData
})
console.log(returnedData); // Shows correct data
console.log(this.state.dbData); // Shows correct data
},100);
我想嘗試尋找這對沒有人爲延遲工作的方式。我將需要在componentWillMount中處理這些數據庫查詢中的3個,因爲我的組件正在加載,並且需要知道在渲染組件之前我已經回收了數據。
謝謝!
使用異步並等待。 – Li357
returnedData = await getDataFromDB(); – David