【问题标题】:React.js: how to map through nested arraysReact.js:如何映射嵌套数组
【发布时间】:2023-01-18 23:58:32
【问题描述】:

假设我有一个对象数组 (myContacts),在 React 中我可以映射数组的每个对象以获取它的 itemindex。我可以使用 item[key] 来获取它的值,但是如果它的值是另一个数组怎么办?..我如何映射它?

这就是我正在尝试的:

const myContacts = [
   {
     name: 'John',
     hobbies: ['swimming', 'skateboard', 'TV']
   },
   {
     name: 'Sarah',
     hobbies: ['Cooking'],
   },
   {
     name: 'Cindy',
     hobbies: ['Shopping', 'Running'],
   },
];
 
function MyPeeps({ myContacts }) {
  return (
    <div>
      {myContacts.map((item, index) => {
        return (
          <div key={index}>
            <p>{item.name}</p>
            {item.hobbies &&
              <ul>
                //if there is a hobbies array for this person, then list each as an `li`
              </ul>
            }
          </div>
        )
      })}
    </div>
  )
}


【问题讨论】:

  • 再次使用map

标签: reactjs


【解决方案1】:

一般来说,你可以这样做:

<ul>{item.hobbies.map(i => <li>i</li>)}</ul>

但更好的想法可能是创建一个 Contact 组件以避免过度嵌套,然后委托给它:

<div key={index}>
    <Contact item={item} />
</div>

【讨论】:

    【解决方案2】:

    如果您确定 hobbies 数组始终存在,您也可以使用 item.hobbies.length &gt; 0

    function MyPeeps({ myContacts }) {
      return (
        <div>
          {myContacts.map((item, index) => {
            return (
              <div key={index}>
                <p>{item.name}</p>
                {item.hobbies && (
                  <ul>
                    {item.hobbies.map((hobby) => (
                      <li key={hobby}>{hobby}</li>
                    ))}
                  </ul>
                )}
              </div>
            );
          })}
        </div>
      );
    }
    

    【讨论】:

      【解决方案3】:
            { 
             item.hobbies.length>0 &&
                <ul>
                    item.hobbies.map((hobby,index)=>{
                    return <li key={index}>{hobby}</li>
                     })
                </ul>
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-17
        • 2019-08-13
        • 2021-09-30
        • 2018-03-09
        • 1970-01-01
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多