首页 > 解决方案 > 如何正确遍历渲染中的对象?

问题描述

嗨,我有一个我正在尝试迭代的对象:

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>
  );
}

标签: javascriptreactjs

解决方案


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>
  );
}

推荐阅读