【问题标题】:Mapping an array of Objects having user-id and getting user-details from this user-ID映射具有用户 ID 的对象数组并从此用户 ID 获取用户详细信息
【发布时间】:2019-09-08 00:44:58
【问题描述】:

我有一个对象数组,比如

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

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

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

【问题讨论】:

  • 映射成什么格式?你试过什么?
  • 用户详细信息在哪里?用户 dp?你能提供给我们实际的数组吗?
  • 用户详细信息是:用户名和用户照片的网址
  • 映射数组以在前端显示。标题和用户详细信息。
  • 谁能帮我解决这个问题?

标签: javascript node.js reactjs mapping


【解决方案1】:

嗯,你的问题不完整,但我会试一试...... 假设您有:

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

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

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多