簡體   English   中英

異步功能無法執行

[英]async function doesn't execute

retrieveData = async () => {
    try {
        //Retrieving values from AsyncStorage
        let voiture = await AsyncStorage.getItem('VOITURE')
        this.state.DBCarName=[];
        this.state.DBCarName = JSON.parse(voiture);
        alert(this.state.DBCarName)
    }
    catch {
        alert('error')
    }
}

該函數的調用:

render() {
                this.retrieveData();

我想使用我的檢索函數,以便為DBCarName狀態分配一個值,以便在Text組件中呈現它。 問題是,在render方法中調用函數時,它返回null,這可能意味着我的函數未執行且數組狀態為空。

關於如何處理這個想法?

發生這種情況是因為您試圖重新分配組件的狀態,而應該使用提供的this.setState函數。 由於您使用的是AsyncStorage和this.state,因此我假設它是一個React Native項目,這里的代碼應如下所示:

class YourComponentName extends React.Component {
  state = {
    DBCarName: []
  }

  retrieveData = async () => {
    try {
      //Retrieving values from AsyncStorage
      const voiture = await AsyncStorage.getItem('VOITURE')
      this.setState({ DBCarName: JSON.parse(voiture) })
    } catch (err) {
        console.log(err)
    }
  }

  render () {...}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM