首页 > 解决方案 > TypeError:传播不可迭代实例的无效尝试

问题描述

编译到 android 并通过 Store 下载后出现错误:

"TypeError: Invalid attempt to spread non-iterable instance"

但是使用“react-native run-android”不会产生错误消息,因此我找不到调试它的好方法。

fetch(url)
  .then(response => response.json())
  .then(response => {
    if (this._mounted) {
      // let dataSource = this.state.articlesDataSource.cloneWithRows(response.data || [])
      //var rowCount = dataSource.getRowCount();
      var rowCount = Object.keys(response.data).length;

      if (refresh == true) {
        prevData = {};
      } else {
        prevData = this.state.articlesData;
      }
      if (propSearch == "" || propSearch == null) {
        newArticlesData = [...prevData, ...response.data];
      } else {
        newArticlesData = response.data;
      }
      if (response.meta.next_page != null) {
        var rowCount = true;
      } else {
        var rowCount = Object.keys(newArticlesData).length;
      }
      if (this._mounted) {
        this.setState({
          isLoading: false,
          //articlesDataSource: this.state.articlesDataSource.cloneWithRows(response.data),
          articlesData: newArticlesData,
          nextPage: response.meta.next_page,
          fetchUrl: url,
          rowCount: rowCount
        });
      }
    }
  })
  .catch(error => {
    this.setState({
      errorFound: true,
      errorMassage: error,
      isLoading: false
    }); 
});

谢谢你的帮助。

标签: javascriptreact-nativereact-native-android

解决方案


这是因为它是运行时错误,而不是“编译时”错误。

是否有与错误相关的行号?基于关于扩展运算符的问题,我假设它是这一行:newArticlesData=[...prevData,...response.data]。我假设您prevData是可迭代的,但是您的响应数据是吗?试试newArticlesData=[...prevData, response.data]

这是一个无效传播运算符使用的示例:

function trySpread(object) {
  let array;
  try {
    array = [...object];
    console.log('No error', array);
  } catch(error) {
    console.log('error', error);
  }
}

// error
trySpread({});
trySpread({foo: 'bar'});
trySpread(4);

// no error
trySpread([]);
trySpread(['foobar']);
trySpread('foobar');


推荐阅读