React:在 componentDidMount 中映射

React: map in componentDidMount

我已经尝试 2 次修改我的 API 获取的对象,方法是映射它,然后通过映射修改这些属性之一,然后再次请求我的 API.

我想如果我现在给你看代码会更清楚:

async componentDidMount() {
  let api = "http://localhost:3000/retrievecommentaries/" + this.props.article;
  let res = await fetch(api);
  let data = await res.json();

  let commentaires = [];

  data.map(commentaire => {
    this.retrieveUser(commentaire.user)
      .then(user => (commentaire.completeuser = user))
      .then((commentaires = [...commentaires, commentaire]));
  });

  console.log(commentaires);

  await this.setState({
    commentarylist: commentaires
  });
}

如您所见,我先获取一篇文章的评论;然后,对于每条评论,我尝试通过评论中包含的用户 ID 检索用户 (commentaire.user)。

我实际上认为这张地图中的 .then 足以确保在调用 this.setState 时,我的新评论列表会很好。

但其实console.log(评论)还可以;我的 this.state.commentarylist 也是;但是当我显示我的 commentarylist 对象时,它没有 completeuser 属性......这可能意味着传递给 setState 的 "commentaires" 也没有 completeuser 属性。 这是奇怪的 IMO,因为我在分配 completeuser 属性之前等待用户被检索,然后推送到我的数组...

所以我有点困惑..

提前致谢! :)

您没有等待 this.retrieveUser 调用,因此 this.setState 将在 commentaires 数组填充任何数据之前被调用。

您可以使用 awaitPromise.all 来确保所有请求都已完成,然后再将结果放入状态。

例子

async componentDidMount() {
  let api = "http://localhost:3000/retrievecommentaries/" + this.props.article;
  let res = await fetch(api);
  let data = await res.json();

  let commentaires = [];

  await Promise.all(
    data.map(async commentaire => {
      let user = await this.retrieveUser(commentaire.user);
      commentaire.completeuser = user;
      commentaires.push(commentaire);
    })
  );

  this.setState({
    commentarylist: commentaires
  });
}