如何进行顺序异步调用并将数据正确传递给兄弟组件?

问题描述 投票:0回答:2

我正在尝试构建一个hackernews克隆作为反应的实践。在这里,我只是尝试使用react来构建它,之后我将使用Redux构建它。这是我的组件结构。

--main
  |--menubar
  |--articles

这是该项目的codepen

我这里有两个问题。

1.)这里我通过状态和props传递数据。我在componentDidMount组件中使用menubar方法调用API,并通过articles组件将其传递给main组件。但它在props方法中通过componentWillReceiveProps接收数据时不会呈现列表。要渲染它,我必须单击News(它与获取数据无关,它只是打印日志),它将调用API方法。当通过props接收数据并设置数据时,如何在this.state.articleList中呈现数据。

2.)在API调用中,我已经定义了仅获得前20个帖子。但是当我点击news时,我每次都会得到随机数量(<20)的帖子。这是为什么 ?由于API调用相同,它不应该呈现相同数量的(20)帖子吗?为何有所不同?

这两个问题是因为异步方法吗?如果是这样我怎么解决它们?

javascript reactjs asynchronous fetch async.js
2个回答
1
投票

实际上,由于异步,我使用async library编辑了fetchdata()并添加了getItems()。

使用map的优点是它将返回一个结果数组,因此我们不需要维护一个数组。

var async = require("async");

fetchdata() {
fetch("https://hacker-news.firebaseio.com/v0/topstories.json")
  .then(res => res.json())
  .then(data => {
    this.setState({ storyList: data }, () => {
      this.getItems(this.state.storyList);
    });
  })
  .catch(err => console.log(`Error fetching data : ${err}`));
  }


getItems(storyList) {
    async.mapLimit(storyList, 10,
      function(item, callback) {
        console.log(item);
        fetch(`https://hacker-news.firebaseio.com/v0/item/${item}.json`)
          .then(res => res.json())
          .then(data => {

            //pass the data here
            callback(null, data);
          });
      },
      function(err, dataArray) {
        if (err) {
          console.error(err.message);
        } else {

          //dataArray will contain an array of results from map
          this.props.getData(dataArray);
        }
      }
    );
  }

1
投票
Hi after getting the data inside getItems binding the data to callback getData as follows

getItems(storyList) {
    var story_list = [];
    async.mapLimit(
        storyList,
        10,
        ((item, callback) =>{
            console.log(item);
            fetch(`https://hacker-news.firebaseio.com/v0/item/${item}.json`)
                .then(res => res.json())
                .then(data => {
                    story_list.push(data);
                    this.props.getData(story_list);
                });
        }),
            ((err) =>{
            if (err) {
                console.error(err.message);
            } else {
                this.props.getData(story_list);
            }
        })
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.