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
相关产品推荐
相关产品推荐

