我有一个对象数组,例如
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/