【问题标题】:React Native FlatList API Error when no more data to fetch当没有更多数据要获取时反应本机 FlatList API 错误
【发布时间】:2020-03-22 11:40:37
【问题描述】:

以下代码运行 fetchData,它从我的 API 中提取数据并将其显示在平面列表中。当我向下滚动平面列表时,API 会加载第 2 页,然后是第 3 页等,并无限分页,这很完美。但是,当我到达 API 数据的末尾时,我收到此错误:TypeError: Invalid attempt to spread non-iterable instance and it's a fatal error。

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>
    );
  }
}

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    检查 api 是否返回一个空数组 []

    或者你可以这样做:

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

    【讨论】:

      【解决方案2】:

      我认为它来自您尝试在您的 json 对象上使用扩展操作,而该对象为空或未定义。为了避免这个问题,只需在调用 setState 方法之前添加一个检查条件即可。

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

      【讨论】:

        猜你喜欢
        • 2018-07-31
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        • 2018-03-29
        • 1970-01-01
        • 1970-01-01
        • 2018-08-26
        • 1970-01-01
        相关资源
        最近更新 更多