javascript - 如何正确遍历渲染中的对象?
问题描述
嗨,我有一个我正在尝试迭代的对象:
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 is not a function
所以我不确定如何更正迭代,因为我之前能够成功地迭代一个字符串数组。我想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
来获取对象中所有键的数组,然后map
:
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>
);
}
推荐阅读
- spring - 在单个事务中运行 Spring Batch 步骤
- python - 如何在 kivy 中更改标签文本?
- macos - SwiftUI:在 macOS 上调整 ColorPicker 的大小
- javascript - 如果条件为真,v-for 循环内的 v-show 将显示所有元素
- multithreading - 你如何在 Perl 线程中使用数组引用?
- javascript - 带有 chart.js 和 PHP 的动态折线图
- php - Laravel Guru:是否可以在 Eloquent 查询中使用新添加的列?
- python - 为大 id 数创建邻接矩阵
- laravel - 如何在新的 laravel 8 中安装 InertiaVue + tailwind?
- django - 没有显示 Django 媒体文件