reactjs - 类型错误 : Cannot read property 'map' of undefined"React

标签 reactjs

我是 React 新手,我正在关注 React 类(class)。下面的代码出现了类似“TypeError: Cannot read property 'map' of undefined”的问题;谁能告诉发生了什么事吗?非常感谢!

import React, { Component } from 'react'

const ListGroup = props => {
    const {items,textProperty,valueProperty} = props;
    return ( 
      <ul className="list-group">
          {items.map(item =>(
         <li key={item[valueProperty]} className="list-group-item">
             {item[textProperty]}
         </li>
          ))}
          
      </ul>
     );
}
 
export default ListGroup;

最佳答案

您似乎没有将 items 属性传递给 ListGroup:

<ListGroup items=[] />

或者,您可以为项目分配默认值:

const {items = [],textProperty,valueProperty} = props;

或者使用 elvis 运算符:

items?.map(item => {})

关于reactjs - 类型错误 : Cannot read property 'map' of undefined"React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66761333/

相关文章:

javascript - 使用样式化组件在第一个焦点上样式化输入边框

html - 我应该如何以惯用的 React 方式访问自定义 HTML 组件的生成子组件?

javascript - 从数组中删除不需要的符号

reactjs - React/RCTBridgeModule.h 文件未找到 RNSSplashScreen

reactjs - useForm 在既不是 React 函数组件的函数中被调用...错误

javascript - 未捕获的不变违规 : Objects are not valid as a React child. 如果您打算渲染子集合,请改用数组

javascript - React : Component Structure, 是否断章取义?

javascript - 如何在React中动态添加属性名称和属性值

javascript - 哪种单元测试设置是正确的?这两个测试是否都检查功能是否正确并且工作正常?

javascript - 有条件地在渲染中添加类不起作用 - React/Gatsby