[英]Why id variable is coming undefined in my react code in todo list Delete component?
import React, { Component } from 'react';
export default class Todo extends Component {
constructor() {
super();
this.state = {
tasks: [
{ id: 1, task: 'CHECK MAILS' },
{ id: 2, task: 'READ ARTICLE' },
],
currentTask: '',
};
}
handleChange = (e) => {
this.setState({
currentTask: e.target.value,
});
};
handleSubmit = () => {
this.setState({
tasks: [...this.state.tasks, { task: this.state.currentTask, id: this.state.tasks.length + 1 }],
currentTask: '',
});
};
handleDelete = () => {
let narr = this.state.tasks.filter((taskObj) => {
return taskObj.id != id;
});
this.setState({
tasks: [...narr],
});
};
render() {
return (
<div>
<input type="text" value={this.state.currentTask} onChange={this.handleChange} />
<button onClick={this.handleSubmit}>SUBMIT</button>
<ul>
{this.state.tasks.map((taskObj) => (
<li>
{' '}
<div key={taskObj.id}>
<p>{taskObj.task}</p>
<button onClick={() => this.handleDelete(taskObj.id)}>DELETE</button>
</div>
</li>
))}
</ul>
</div>
);
}
}
Here in this code error is coming that id is undefined in line 35(return taskObj.id;= id;
).在此代码中出现错误,即第 35 行中的 id 未定义(return
taskObj.id;= id;
)。 I am not able to resolve the error.我无法解决错误。 Since I have defined id in tasks array then also it is showing error.
由于我在任务数组中定义了 id,所以它也显示错误。 I am making a todo list using react.
我正在使用 react 制作一个待办事项列表。
You need to pass the id as a parameter of the function like this:您需要将 id 作为 function 的参数传递,如下所示:
handleDelete = (id) => {
instead of:代替:
handleDelete = () => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.