您好,我有一个对象要遍历:
this.props.recentMessages = {
'4383456789': {
'number': '4383456789',
'created': 1531142643,
'text': "Hello World"
},
'5141234567': {
'number': '5141234567'
'created': 1531173846
'text': "This is the second text"
}
}
但我现在遇到的问题是它说 this.props.recentMessages.map 不是一个函数
所以我不确定我将如何更正迭代之前成功地遍历了一个字符串数组。在遍历它之前,我想先检查 this.props.recentMessages
是否存在。
render() {
return (
<div className="menu-tab">
<LeftNav className="chat-left-nav">
{this.props.recentMessages
? this.props.recentMessages.map(function(thread, index) {
<LeftNavSC.Item>
<span key={index} className="contact-name">
{thread.number}
</span>
<br />
</LeftNavSC.Item>;
})
: ""}
</LeftNav>
</div>
);
}
最佳答案
您不能像处理数组那样使用 map
遍历对象。你可以使用 Object.keys
获取对象中所有键的数组,并在其上映射
:
render() {
const { recentMessages } = this.props;
return (
<div className="menu-tab">
<LeftNav className="chat-left-nav">
{recentMessages &&
Object.keys(recentMessages).map(key => (
<LeftNavSC.Item key={key}>
<span className="contact-name">
{recentMessages[key].number}
</span>
<br />
</LeftNavSC.Item>
))}
</LeftNav>
</div>
);
}
关于javascript - 如何正确地遍历渲染中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51369079/