如何解决类型错误:无法读取未定义的属性“item_name”
我是 React js 的初学者,我正在尝试创建待办事项应用程序。基本上这里有一个文本输入。当我运行“ npm start”并在我的端口上显示我的预期输出时,我的应用程序运行完美。但是当我为我的列表添加一些东西时它没有添加任何东西并显示这个“TypeError:无法读取未定义的属性'newItem'”错误。
这是我的代码..
import React,{Component} from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
newItem:"",list:[]
}
}
updateInput(key,value){
//update react state
this.setState(
{
[key]:value
}
);
}
addItem(){
//crete item with unique id
const newItem = {
id: 1 + Math.random(),//error here
value: this.value.newItem.slice()
};
//copy of current list of item
const list = [...this.state.list];
//add new item to list
list.push(newItem);
//update item with new list and reset newitem input
this.setState(
{
list,newItem:""
}
);
}
deleteItem(id){
//copy current list of item
const list = {...this.state.list};
//filter out item being deleted
const updatedList = list.filter( item => item.id !== id);
this.setState({
list: updatedList
});
}
render(){
return(
<div className="App">
<div>
Add an items...
<br/>
<input
type="text"
placeholder="Add your task.."
value={this.state.newItem}
onChange={e=> this.updateInput("newItem",e.target.value)}
/>
<button
onClick={()=> this.addItem()} //error here
>
Add
</button>
<br/>
<ul>
{this.state.list.map( item=>{
return(
<li key={item.id}>
{item.value}
<button
onClick={()=> this.deleteItem(item.id)}
>X</button>
</li>
)
})}
</ul>
</div>
</div>
);
}
}
export default App;
Chrome 浏览器控制台显示类似 Uncaught TypeError: Cannot read property 'newItem' of undefined 我已经注意到我的错误行作为注释 //error.
解决方法
将代码中的 value: this.value.newItem.slice()
更改为 this.state.newItem.slice()
,这修复了 addItem() 方法上发生的错误。由于没有属性作为类 App 的值,这会导致未定义错误。
并将 deleteItem() 方法中的 const list = {...this.state.list};
更改为 const list = [...this.state.list];
,这也会导致尝试删除待办事项时出错。
如果您觉得有帮助,请为解决方案点赞。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。