React To-Do应用:删除项目,但保持单独状态

时间:2018-08-07 19:54:07

标签: javascript reactjs

我的React应用程序遇到了问题。到目前为止,已有足够的功能来将待办事项添加到列表中,通过索引将其删除并标记为完成(文本装饰:直通)。

当我删除一个已经划掉的项目时,我希望其他项目保持它们自己的状态,但是不会。这就是我的意思。

Let's remove the crossed out item Why is the bottom one crossed out now? 这是我的代码

ToDoApp.js

    import React from 'react';

import Header from './Header';
import AddToDo from './AddToDo';
import FilterToDo from './FilterToDo';
import ToDoList from './ToDoList';
import ListButtons from './ListButtons';

export default class ToDoApp extends React.Component {
  state = {
    toDos: []
  };
  handleAddToDo = (toDo) => {
    if (!toDo) {
      return "Nothing was added!";
    }
    this.setState((prevState) => ({
      toDos: prevState.toDos.concat([toDo])
    }));
  };
  handleRemoveToDo = (removeIndex) => {
    this.setState((prevState) => ({
      toDos: prevState.toDos.filter((toDo, index) => index !== removeIndex)
    }));
  };
  render() {
    return (
      <div>
        <Header />
        <AddToDo
          handleAddToDo={this.handleAddToDo}
        />
        <FilterToDo />
        <ToDoList
          toDos={this.state.toDos}
          handleRemoveToDo={this.handleRemoveToDo}
        />
        <ListButtons />
      </div>
    );
  };
};

ToDoList.js

import React from 'react';
import ToDoListItem from './ToDoListItem';

const ToDoList = (props) => (
  <div>
    <h3>To Do List</h3>
    <div>
      {props.toDos.map((toDo , index) => (
        <ToDoListItem
          key={index}
          index={index}
          toDoTitle={toDo}
          handleRemoveToDo={props.handleRemoveToDo}
        />))}
    </div>
  </div>
);

export default ToDoList;

ToDoListItem.js

import React from 'react';

export default class ToDoListItem extends React.Component {
  state = {
    done: false
  };
  handleDoneTrigger = () => {
    this.setState((prevState) => ({ done: !prevState.done }));
  };
  render() {
    return (
      <div>
        <p
          className={this.state.done ? "done" : ""}
        >{this.props.toDoTitle}</p>
        <button onClick={(e) => {
          this.props.handleRemoveToDo(this.props.index)
        }}>Remove</button>
        <button onClick={this.handleDoneTrigger}>Done</button>
      </div>
    );
  }
};

1 个答案:

答案 0 :(得分:3)

问题在于这段代码:

<ToDoListItem
      key={index}
      index={index}
      toDoTitle={toDo}
      handleRemoveToDo={props.handleRemoveToDo}
    />))}

将索引设置为ToDoListItem的键。代替索引,为每个元素分配一个唯一的键,因为当您删除一个项目时,其索引分配给列表中的下一个项目。

这将有助于进一步深入研究:https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318