使用React JS删除列表中的特定项目

时间:2018-08-13 02:30:20

标签: reactjs

因此,我试图从其当前数组中删除待办事项,但它不起作用。服务器启动时,我尝试使用console.log,但未传递任何参数。

Todos返回数组[]。

这是我的代码:

>>> df
       a  b         c  sum_c_3
0    one  x  1.296379    99.99
1    one  y  0.201266    99.99
2    one  x  0.953963    99.99
3    one  y  0.322922    99.99
4    two  x  0.887728    99.99
5    two  y -0.154389    99.99
6    two  x -2.390790    99.99
7  three  x -1.218706    99.99
8   four  x -0.043964    99.99
>>> 

我的返回码是这样的:

handleTodoDelete = (deleteTodo) => {
    const remainingItems = this.state.todo.filter (todo => {  
      return todo !== deleteTodo;
    });

    this.setState({
      todos: remainingItems
    });

  }

2 个答案:

答案 0 :(得分:0)

尝试做:

const remainingItems = this.state.todos.filter (todo => {  
  return todo !== deleteTodo;
});

this.setState({
  todos: remainingItems
});

或者尝试做:

const remainingItems = this.state.todo.filter (todo => {  
  return todo !== deleteTodo;
});

this.setState({
  todo: remainingItems
});

似乎您想在状态中同时使用todostodo,而不是两者同时使用。

这里有一些带有过滤器的工作代码,也许可以帮助您进行比较:

const app = document.querySelector('#app');

const todoOne = { id: 1, description: "Code this." };
const todoTwo = { id: 2, description: "Make that." };

const todos = [
  todoOne,
  todoTwo,
];

const todoToRemove = todoOne;

const removedTodos = todos.filter(
  (todo) => todo.id != todoToRemove.id
)

app.innerHTML = `
  <p>To Dos (Original): <br>${JSON.stringify(todos)}</p>
  <p>To Dos (Deleted): <br>${JSON.stringify(removedTodos)}</p>
`;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Snippet</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

答案 1 :(得分:0)

在react redux应用程序中更改列表或对象时,应始终创建另一个列表或对象。

最好的方法是通过传播算子。

handleTodoDelete = (deleteTodo) => {
    let state = this.state;
    let newTodo = [...state.todo.filter(todo => todo.id !== deleteTodo.id)];
    state.todo = newTodo;
    this.setState({ state });
}