如何迭代作为对象嵌套在对象中的数组

时间:2020-10-14 04:47:49

标签: javascript json reactjs

我有一个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

2 个答案:

答案 0 :(得分:0)

在初始渲染时,要素中还没有数据。这样的使用条件->

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

答案 1 :(得分:0)

异步加载数据时,组件的初始渲染将无法访问数据(数据将为undefined)。

应该对您的组件进行编码,以通过显示不同的视图(例如加载动画)来应对这种情况。

这可以通过在渲染组件之前简单地检查是否定义了props.features来实现:

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

  return (
    <div>
      <div>
        <div className={styles.text}>
          <p>{props.description}</p>
          <ul>
            {
                /** Conditionally show only when props.features has a truthy value **/
                !!props.features && props.features.map((feature) => (
                    <li>{feature}</li>
                ))
            }
          </ul>
        </div>
      </div>
    </div>
  );
}

要在加载数据时显示另一个组件/文本,可以使用三元语句:

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

  return (
    <div>
      <div>
        <div className={styles.text}>
          <p>{props.description}</p>
          <ul>
            {
                /** Ternary statement to show components when props.features is a truthy value 
                    or loading when a falsy value **/
                props.features ? 
                    props.features.map((feature) => (
                        <li>{feature}</li>
                    )) :
                    "Loading..."
            }
          </ul>
        </div>
      </div>
    </div>
  );
}