簡體   English   中英

React-Native的睡眠功能?

[英]Sleep function for React-Native?

因此,我試圖通過Google Places API獲取React Native中的某些位置來獲取所有“位置”。 問題是,在第一次調用API之后,Google只返回20個條目,然后返回next_page_token ,以附加到同一個API調用url 因此,我提出另一個請求,以便立即獲得接下來的20個位置,但是在令牌實際變為有效之前會有一個小的延遲(1-3秒),因此我的請求出錯。

我試過做:

this.setTimeout(() => {this.setState({timePassed: true})}, 3000);

但它被應用程序完全忽略了......有什么建議嗎?

更新

我在componentWillMount函數中執行此操作(在定義變量之后),並在此行之后調用setTimeout

axios.get(baseUrl)
.then((response) => {
   this.setState({places: response.data.results, nextPageToken: response.data.next_page_token });

});

我的理解是你試圖根據另一個提取的結果進行提取。 所以,你的解決方案是使用TimeOut來猜測請求何時完成,然后再做另一個請求,對嗎?

如果是,也許這不是解決問題的最佳方案。 但是以下代碼是我如何使用超時:

// Without "this"
setTimeout(someMethod,
    2000
)

我將采取的方法是等待提取完成,然后我將使用不同的參數再次使用回調來進行相同的提取,在您的情況下,使用nextPageToken 我使用ES7 async和await語法執行此操作。

// Remember to add some stop condition on this recursive method.
async fetchData(nextPageToken){
    try {
        var result = await fetch(URL)
        // Do whatever you want with this result, including getting the next token or updating the UI (via setting the State)
        fetchData(result.nextPageToken)
    } catch(e){
         // Show an error message
    }
}

如果我誤解了某些內容或者您有任何疑問,請隨時提出!

我希望它有所幫助。

試試這個對我有用:

  async componentDidMount() {
     const data = await this.performTimeConsumingTask();

        if (data !== null) {
       // alert('Moved to next Screen here');
    this.props.navigator.push({
        screen:"Project1.AuthScreen"})
        }
  }
  performTimeConsumingTask = async() => {
    return new Promise((resolve) =>
      setTimeout(
        () => { resolve('result') },
        3000
      )
    );
  }

暫無
暫無

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

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