如何显示从多个API页面获取的嵌套数组数据

时间:2019-06-19 06:50:25

标签: arrays reactjs react-native

我正在尝试显示来自API的大量文章数据。 API数据分页为每页20个对象。我已经设法将它们存储在一个数组中,但是现在它是一个数组,但是其中嵌套了多个数组,如果听起来不令人困惑,那么我将尝试访问该数组中的嵌套数组。

所以现在看起来像这样:mainArray.nestedArray.articles(object)我想将其缩短为mainArray.articles,而无需使用nestedArray

我尝试了ES6并进行串联,但返回:

    undefinedundefined[object Object]undefinedundefined[object Object][object Object]undefinedu

当我使用

    for(let i=latestPage; i>1; i--){
        apiArticles += apiArticles.concat(allArticles[i]);
    }

我也怀疑我无法合并它们,因为它们是一个Promise数组:有没有办法在setState段的主数组中显示所有嵌套数组的数据?

    Array [
      Promise {
        "_40": 0,
        "_55": null,
        "_65": 0,
        "_72": null,
      },
      Promise {
        "_40": 0,
        "_55": null,
        "_65": 0,
        "_72": null,
      },
      Promise {
        "_40": 0,
        "_55": null,
        "_65": 0,
        "_72": null,
      },
      Promise {
        "_40": 0,
        "_55": null,
        "_65": 0,
        "_72": null,
      },

完整代码

componentDidMount(){
  let allArticles = [];  
  var apiArticles = [];

  fetch(BASE_URL)
    .then(response => response.json())
    .then((responseJson) => {
      return fetch(responseJson._links.last.href)
    })
    .then(response => response.json())
    .then((responseJson) => {
      var captured = /page=([^&]+)/.exec(responseJson._links.self.href)[1]; 
      var latestPage = captured ? captured : '100';

      for (let i=latestPage; i>1; i--) {
        allArticles.push(fetch(BASE_URL + '&page=' + i)
          .then(res => res.json()));
      }

      console.log(allArticles);

      // for (let i=latestPage; i>1; i--){
      //   apiArticles = [...allArticles[i]];
      // }

      Promise.all(allArticles)
        .then(articlesJson => this.setState({
          loading: false,
          dataSource: articlesJson[1].articles.reverse()
   }))
})

我应该能够通过以下方式访问所有文章

articlesJson.articles.reverse()

代替

articlesJson[1].articles.reverse()

这是我的json响应的示例(略作编辑)。这是nestedArray [1] .articles

之一
"articles": Array [
      Object {
        "_links": Object {
          "self": Object {
            "href": "https://api.example.com/v2/articles/9113",
          },
        },
        "content": "<p>test</p>",
        "created_at": 1555319812,
        "id": 9113,
        "image": "https://example.jpeg",
        "owner_id": 14415,
        "owner_name": "TEST",
        "owner_type": "organization",
        "short_description": "short test",
        "slug": "slug test",
        "title": "test title",
        "total_comment": 0,
        "total_like": 0,
        "updated_at": 1555319841,
      },

0 个答案:

没有答案