首页 > 解决方案 > 如何迭代嵌套在对象中的数组作为道具

问题描述

我有一个我正在解析数据的 JSON 文件,但我正在尝试映射一个子数组(嵌套在一个对象中)。但是,我收到一个错误,说数组不可迭代。我将数组记录到打印数组的控制台,但是当我检查它的类型时,它显示“对象”。

这是我的代码:

export default function Projects({ children, ...props }) {

  return (
    <div>
      <div>
        <div className={styles.text}>
          <p>{props.description}</p>
          <ul>
            {props.features.map((feature) => (
              <li>{feature}</li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
}

JSON 文件:

[
  {
    "id": 1,
    "name": "Netflix Clone",
    "img": "/netflix-clone.jpg",
    "direction": "row",
    "description": "This project is a minimalistic Netflix clone utilising Firefox for storage and authorisation. It utilises Styled Components for styling, compound components, large-scale React architecture, and custom hooks.",
    "features": [
      "React",
      "Styled Components",
      "Compound components",
      "Large-Scale React Architecture",
      "Firebase (Firestore & Auth)",
      "Functional components",
      "Firebase (Firestore & Auth)",
      "Custom hooks"
    ]
  },
]

错误:

TypeError: Cannot read property 'map' of undefined

标签: javascriptjsonreactjs

解决方案


在初始渲染时,特征中还没有数据。像这样使用条件 ->

props && props.features && props.features.map((feature) => (
          <li>{feature}</li>
        ))}

推荐阅读