繁体   English   中英

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

[英]How to make to make sequential async calls and pass data to a sibling component properly?

我正在尝试建立一个hackernews克隆作为对reactjs的一种实践。 在这里,我尝试仅使用react构建它,稍后再使用Redux构建它。 这是我的组件结构。

--main
  |--menubar
  |--articles

这是该项目的代码笔

我在这里有两个问题。

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

2.)在API调用中,我已定义为仅获取前20个帖子。 但是,当我单击news ,每次都会得到随机数量的(<20)个帖子。 这是为什么 ? 由于API调用相同,因此是否应该呈现相同数量的(20)个帖子? 为什么不同?

这两个问题都是由于异步方法引起的吗? 如果可以,我该如何解决?

实际上,由于异步,我使用异步库对其进行了编辑,并编辑了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);
        }
      }
    );
  }
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);
            }
        })
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM