尝试从React中的对象数组中删除项目

时间:2019-08-12 00:49:19

标签: javascript arrays reactjs components javascript-objects

我正在学习React。我正在尝试自行构建一个简单的待办事项应用程序,以学习和练习该库。我已经在父级组件中传递了任务列表,并将它们作为道具传递给了子级组件。我还可以使用map()方法将其输出到子组件中。但是,我不知道如何删除项目。我已经尝试过在线搜索,但是无法根据我的用例调整他们的解决方案。任何帮助将不胜感激!

父组件

import React, { Component } from 'react';
import './styles/components/App.css';
import Todos from './components/Todos'

class App extends Component {
  state = {
    todos: [
      { task: 'Study React', id: 1 },
      { task: 'Build something with it',  id: 2 },
      { task: 'Apply for jobs', id: 3 },
    ],
  }
  render(){
    return (
      <div className="App">
          <Todos todos={this.state.todos} />
      </div>
    );
  }
}

export default App;

子组件

import React, { Component } from 'react';
import '../styles/components/Todos.css'

class Todos extends Component {
    render() {
        let { todos } = this.props;

        let todoList = todos.map(( todo => {
            return (
                <div className="todos" key={todo.id}>
                    <div>{ todo.task }</div>
                </div>
            )
        }));
        return (
            <div onClick={this.deleteTask}>{ todoList }</div>
        )

    }
    deleteTask() {
        // checks if method is working
       console.log('working');
       // code to delete 
    }
}

export default Todos

1 个答案:

答案 0 :(得分:1)

父组件

import React, { Component } from 'react';
import './styles/components/App.css';
import Todos from './components/Todos'

class App extends Component {
  state = {
    todos: [
      { task: 'Study React', id: 1 },
      { task: 'Build something with it',  id: 2 },
      { task: 'Apply for jobs', id: 3 },
    ],
  };

  // Event and data put in same Component.
  deleteTodo(id) {
    let workTodos = [...this.state.todos];
    const deleteIndex = workTodos.findIndex(todo => todo.id === id);
    workTodos.splice(deleteIndex, 1);
    this.setState({
      todos: [...workTodos]
    })
  }

  render(){
    // Use props give Todos Component the data and events to render dom
    return (
      <div className="App">
          <Todos
            todos={this.state.todos}
            deleteTodo={this.deleteTodo.bind(this)}
          />
      </div>
    );
  }
}

export default App;

子组件

import React, { Component } from 'react';
import '../styles/components/Todos.css'

class Todos extends Component {
  render() {
    // Receiving events and data form props
    let { todos, deleteTodo } = this.props;

    // Click div trigger deleteTodo, It can execute deleteTodo in App component
    return todos.map(( todo => {
        return (
            <div
              className="todos"
              key={todo.id}
              onClick={() => { deleteTodo(todo.id) }}
            >
                <div>{ todo.task }</div>
            </div>
        )
    })); 
  }
}

export default Todos

就像提交一样,将删除事件放在App组件中,然后使用道具在Todos组件中触发它,如果有任何疑问,请告诉我。