因此,基本上,我试图构建一个消息页面,以便用户可以与其他用户一起查看其所有活动线程。我要完成的事情之一是在列表中显示每个线程的一些基本信息,然后他们才能单击它并进入详细信息和实际线程本身。我遇到的问题是当我试图显示他们正在聊天的用户名时。在此页面的组件中,我首先像这样提取所有线程:(请注意,我正在使用redux,并且this.props
被分派到正确的提取调用中)
componentDidMount(){
this.props.getMessageThreads()
.then(response => {
this.setState({threads: response})
})
}
每个线程都有一个字段user1
和user2
,这是两个互相聊天的用户的ID。在我的渲染中,我只是试图显示一个包含当前用户正在聊天的其他用户的所有名称的表。我检查哪个ID与当前用户匹配,并将不是当前用户的ID保存在collaboratorID
变量中。当我必须使用此collaboratorID
进行另一个访存调用时,就会出现问题,并且由于某种原因,它不想正确显示它。我使用console.log()
进行了调试,并指出包括getName(id)
中的所有提取调用都返回了正确的响应。
在我的render()
中:
{this.state.threads.map((thread, index) => {
let collaboratorID;
thread.user1 === this.props.user.id ? collaboratorID = thread.user2 : collaboratorID = thread.user1
return (
<TableRow key={index}>
<TableCell component="th" scope="row">
{this.getName(collaboratorID)}
</TableCell>
</TableRow>
)
})}
我的getName(id)
函数:
getName(id){
this.props.loadAnotherUser(id)
.then(response => {
return response.profile.display_name
})
}
现在它根本不显示任何内容,该表为空白。在弄乱它之前,我可以通过具有名称状态数组并在for循环内执行this.setState({ names: [...this.state.names, response.profile.display_name] })
来使其显示名称,但是名称始终显示混乱并混合在一起。这种方式似乎也多余且不必要,但我可能是错的。无论如何,我会很感激对此的任何投入。预先感谢!
答案 0 :(得分:2)
仅当状态更新时,react才重新渲染,我认为您可以这样尝试:
async componentDidMount() {
// first, get threads data.
const threads = await this.props.getMessageThreads();
// then we need to get displayName for every single thread
const threadsWithDisplayName = await Promise.all(
threads.map((t) =>
this.props
.loadAnotherUser(t.user1 === this.props.user.id ? t.user2 : t.user1)
.then((response) => ({
...t,
displayName: response.profile.display_name,
}))
)
);
// save the result into state
this.setState({ threads: threadsWithDisplayName });
return Promise.resolve();
}
,然后只需访问渲染中的displayName
。
{this.state.threads.map((thread, index) => (
<TableRow key={index}>
<TableCell component="th" scope="row">
{thread.displayName}
</TableCell>
</TableRow>
)}
我尚未实际测试上面的代码,它可能不是100%正确,但想法可能是这样的。