2017-07-27 46 views
0

我需要從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個,因爲我的組件正在加載,並且需要知道在渲染組件之前我已經回收了數據。

謝謝!

+0

使用異步並等待。 – Li357

+1

returnedData = await getDataFromDB(); – David

回答

0

當組件初始化時,使用componentDidMount生命週期鉤子獲取異步數據。這應該在使用異步獲取的數據的組件或多個組件使用的數據的最接近的共同祖先中完成。原因是在異步檢索完成後減少重新呈現的組件的數量。

請記住,在異步數據可用之前,您還需要爲加載狀態。

以下是原理的基本示例。

class ComponentThatRequiresAsyncData extends PureComponent { 
    constructor(props) { 
     super(props); 

     // initialize state 
     this.state = { 
      data: null 
     } 
    } 

    // handle async operation in this lifecycle method to ensure 
    // component has mounted properly 
    componentDidMount() { 
     axios.get("some_url") 
      .then((response) => { 
       // once you have your data use setState to udpate state 
       this.setState((prevState, props) => { 
        return { data: response.data }; 
       }) 
      }) 
      .catch((error) => { 
       // handle errors 
      }); 
    } 

    render() { 
     const { data } = this.state; 
     return (
      { 
       data ? 
        <WhatEverIWantToDoWithData data={ data } /> : 
        <p>Loading...</p> 
      } 
     ); 
    } 
} 

對於因事件而需要加載的數據,例如按鈕點擊,使用相同的想法。而不是使用componentDidMount你可以自己製作方法,通過你的http調用的then方法中的setState進行異步調用和更新狀態。只要確保在構造函數中綁定了方法的this上下文,如果您將它用作事件處理函數。

希望這會有所幫助。如果您有任何疑問,請詢問!

相關問題