过滤函数返回空数组?

时间:2018-11-20 21:48:26

标签: javascript arrays reactjs filter

因此,当我在此处调用handleRemove函数时,如果返回并返回console.log el,则会得到每个待办事项。但是,如果我返回console.log el [index]或el [index] .id,我只会得到一个空数组。我已经研究了Array.prototype.filter方法的文档,但是我不明白我在这里做错了什么。

import React, { Component } from 'react';
import TodoInput from './todo-input';
import TodoList from './TodoList';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      todos: [],
      inputValue: ''
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
  };

  handleChange = (e) => {
    e.preventDefault();
    this.setState({
      inputValue: e.target.value
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const newTodo = {
      title: this.state.inputValue,
      id: Date.now(),
      done: false
    };
    this.setState((prevState) => ({
      todos: [...prevState.todos, newTodo],
      inputValue: ''
    }));
  }

  handleRemove = (e) => {
    e.preventDefault();
    const newTodos = this.state.todos.filter((el, index) => el[index]);
    // this.setState((prevState) => ({
    //   todos: newTodos
    // }));
    console.log(newTodos);
  }

  render() {
    return (
        <div>
          <TodoInput
          value={this.state.inputValue}
          onChange={this.handleChange}
          onSubmit={this.handleSubmit}
          />
          <TodoList 
          todosArr={this.state.todos}
          onRemove={this.handleRemove}
          />
        </div>
    );
  }
}

export default App;

TodoList.js

import React, { Component } from 'react';
import TodoItem from './TodoItem';

class TodoList extends Component {
  render() {
    const mappedTodos = this.props.todosArr.map((todo, index) => 
      <TodoItem
      key={index}
      todoTitle={todo.title}
      handleRemove={this.props.onRemove}
      todoId={todo.id}
      />
    );

    return (
      mappedTodos
    );
  }
}

export default TodoList;

1 个答案:

答案 0 :(得分:1)

过滤器期望的响应是对,因此您需要将el与某种条件(例如ID)进行比较。

演示

https://repl.it/@AnonymousSB/SO53402083

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: [
        { id: 123, value: 'Water the dog' },
        { id: 456, value: 'Rake the floor' }
      ]
    }
  }
  handleRemove(e, id) {
    const todos = this.state.todos.filter(todo => todo.id !== id)
    this.setState({ todos })
  }
  render() {
    return (
      <section style={{width: 500}}>
        <ul>
          {this.state.todos.map(todo => {
            return <li onClick={(e) => this.handleRemove(e, todo.id)}>{todo.value}</li>
          })}
        </ul>
      </section>
    );
  }
}

export default App;