我有一个对象数组,比如
const array = [{
text: 'some text',
userID: '1'
},
{
text: 'another text',
userID: '2'
}
]我必须在React中映射这个数组,并通过userID获取用户名和用户dp等用户详细信息。我该怎么做呢?我使用的是React、MongoDB、NodeJS、Express。
在我的前端代码中映射数组时,我尝试调用api来获取用户详细信息。它不能正确呈现,因为我后来了解到,我们不应该在render()方法中调用api。
发布于 2019-04-19 22:35:15
你的问题还不完整,但我会试一试……假设你有:
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 })
}; 然后,您可以通过访问您的状态来访问渲染中的详细信息。
https://stackoverflow.com/questions/55733155
复制相似问题