You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React列表增删功能实现与相关报错问题排查求助

React列表增删功能问题修复方案

问题1 点击删除按钮报错Cannot read properties of undefined (reading 'deleteItem')

错误原因

ListItem组件内删除按钮的点击事件存在拼写错误:你将this.props误写为this.prop,缺少末尾的s,导致无法读取传入的deleteItem方法。

修复方法

将对应行代码替换为:

<button onClick={() => this.props.deleteItem(item.key)}>Ta bort</button>

问题2 新增列表项报错TypeError: e.render is not a function

错误原因

存在3处语法错误:

  • React 类组件的渲染逻辑必须定义在render()方法中,你直接将 JSX 返回逻辑写在了ListItem的constructor构造函数里,框架找不到标准的render方法触发报错
  • 数组map的回调参数名与内部使用的变量名不匹配:items.map(items => {的回调参数是items,但内部实际调用的是item.text
  • 列表项的key属性写为了固定字符串"item.key",没有绑定动态的item.key值

修复方法

将ListItem组件替换为以下代码:

class ListItem extends React.Component {
  render() {
    const items = this.props.items;
    const ListItems = items.map(item => {
      return <div className="list" key={item.key}>
              <p>{item.text}</p>
            </div>
    })
    return (
      <div>{ListItems}</div>
    )
  }
}

内容的提问来源于stack exchange,提问作者rvvds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:54:10