首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >映射具有user-id的对象数组,并从此user-ID获取user-details

问映射具有user-id的对象数组,并从此user-ID获取user-details
EN

Stack Overflow用户
提问于 2019-04-18 01:34:35
回答 1查看 408关注 0票数 1

我有一个对象数组,比如

代码语言:javascript
复制
const array = [{
    text: 'some text',
    userID: '1'
  },
  {
    text: 'another text',
    userID: '2'
  }
]

我必须在React中映射这个数组,并通过userID获取用户名和用户dp等用户详细信息。我该怎么做呢?我使用的是React、MongoDB、NodeJS、Express。

在我的前端代码中映射数组时,我尝试调用api来获取用户详细信息。它不能正确呈现,因为我后来了解到,我们不应该在render()方法中调用api。

EN

回答 1

Stack Overflow用户

发布于 2019-04-19 22:35:15

你的问题还不完整,但我会试一试……假设你有:

代码语言:javascript
复制
const array = [{
    text: 'some text',
    userID: '1'
  },
  {
    text: 'another text',
    userID: '2'
  }
];

你可以做到

代码语言:javascript
复制
async componentDidMount() {
  // I dont know where the array come from, ill assume it comes from the props...
  const { array } = this.props;
  // Promise.all returning an array of userDetails in the same order than the given array
  const userDetails = await Promise.all(array.map(({userID}) => fetch(`apiUrl/${userID}`);
  this.setState({ userDetails })
}; 

然后,您可以通过访问您的状态来访问渲染中的详细信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55733155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档