簡體   English   中英

當沒有更多數據可獲取時反應本機FlatList API錯誤

[英]React Native FlatList API Error when no more data to fetch

以下代碼運行fetchData,它從我的API中提取數據並將其顯示在平面列表中。 當我向下滾動到平面列表時,API會無限頁面分頁加載第2頁,然后加載第3頁,依此類推。 但是,當我到達API數據的末尾時,會出現以下錯誤:TypeError:散布不可迭代實例的無效嘗試,這是一個致命錯誤。

fetchData = async () => {
    const response  = await fetch(
    'MYAPI&page=' + this.state.postalCode);
    const json = await response.json();
    this.setState(state => ({
     data: [...state.data, ...json]
   }));
 };

handleMore = () => {
 this.setState(state => ({ page: this.state.page + 1 }), () => this.fetchData());
};

  render() {

    return (
<View>

      <FlatList
        data={this.state.data}
        onEndReached={this.handleMore}
        onEndThreshold={0}
        renderItem={({ item }) =>

<Text>{item.id} - {item.title}</Text>

     }
      keyExtractor={item => item.id} />

</View>
    );
  }
}

檢查api是否返回空數組[]

或者您可以這樣做:

fetchData = async () => {
  const response  = await fetch(
  'MYAPI&page=' + this.state.postalCode);
  const json = await response.json();
  this.setState(state => ({
    data: [...state.data, ...(json || [])]
  }));
};

我認為它來自您嘗試在此對象為null或未定義時在json對象上使用傳播操作。 為避免此問題,只需在調用setState方法之前添加檢查條件即可。

const json = await response.json();
if (json !== undefined && json !== null) {
   this.setState(state => ({
      data: [...state.data, ...json]
    }));
}

暫無
暫無

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

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