简体   繁体   English

为什么 id 变量在我的待办事项列表删除组件的反应代码中未定义?

[英]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.

相关问题 为什么我的组件没有在此待办事项列表应用程序中重新呈现? - Why is my component not rerendering in this todo list app? 为什么 action 没有更新我在这个待办事项列表中的组件? - Why is action not updating my component in this todo list? 我无法删除使用 react 创建的待办事项列表中的项目,请帮助我解决代码中的错误 - I am not able to delete items in my todo list made with react, please help me with error in my code 为什么我无法删除待办事项列表中的待办事项? - Why I cant delete todo item in todo list? 在ReactJS代码中为待办事项列表应用映射未定义 - Map undefined in ReactJS code for todo list app 为什么我的 ID 在我的 React 组件中失败? - Why is my id failing in my React component? 为什么我的 React 组件图标会以 typeof 对象的形式出现? - Why is my React component icon coming out as a typeof object? 为什么我的React组件的props未定义 - Why are the props undefined for my React Component 通过id undefined反应删除 - React delete by id undefined 我在 React 上尝试在我的待办事项列表上呈现过滤器功能时收到“未捕获的类型错误:未定义不是函数” - I got an "Uncaught TypeError: undefined is not a function" while trying to render the filter functionality on my todo list on React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM