javascript - 映射具有用户 ID 的对象数组并从该用户 ID 获取用户详细信息

标签 javascript node.js reactjs mapping

我有一个对象数组,例如

const array = [{
    text: 'some text',
    userID: '1'
  },
  {
    text: 'another text',
    userID: '2'
  }
]

我必须在 React 中映射这个数组,并通过 userID 获取用户详细信息,例如用户名和 user-dp。我该怎么办呢。我正在使用 React、MongoDB、NodeJS、Express。

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

最佳答案

好吧,你的问题不完整,但我会尝试一下...... 假设您有:

const array = [{
    text: 'some text',
    userID: '1'
  },
  {
    text: 'another text',
    userID: '2'
  }
];

你可以做到

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 })
}; 

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

关于javascript - 映射具有用户 ID 的对象数组并从该用户 ID 获取用户详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733155/

相关文章:

javascript - React - 每秒更新组件而不重新渲染整个表单

javascript - 当一个元素增加时增加所有元素的高度(等高列)

android - 当新消息发送给用户并且应用程序处于后台时,我没有收到推送通知

node.js - 设置接受的 CA 列表并使用 chai-http 忽略 SSL 错误

javascript - 如何使用socket.io从客户端向服务器插入数据?

javascript - jquery悬停并停留直到鼠标移出

javascript - 如何从 servlet 中使用 Javascript 创建的 jsp 获取表值

javascript - Promise.map 内的 Promise.map

mysql - react 正在将数据发布到控制台,但数据未成功使其成为 mysql 数据库

string - 在 React 中将组件的状态添加到字符串中