【问题标题】:Deleting an array element of a react state删除反应状态的数组元素
【发布时间】:2021-01-24 13:52:30
【问题描述】:

我知道这不是反应问题,而且我不擅长编码。谁能告诉我为什么我的代码运行得这么奇怪!

我的项目是一个简单的待办事项列表。我有 3 个组件。

  1. 主应用组件
  2. TodoList 组件
  3. TodoItem 组件

我想在用户单击删除图标时删除 TodoItem。

这是 app.js

const [todoLists, setTodoLists] = useState([]);

function setTodoList(index, setFunction) {
    setTodoLists(prevTodoLists => {
        const newTodoLists = [...prevTodoLists]
        newTodoLists[index] = {...setFunction(newTodoLists[index])};
        console.log([...newTodoLists])
        return [...newTodoLists];
    });
}

return (
    <section className="todoContainer" id="todocontainer">
        {
            todoLists.map((todoList, index) => {
                return <TodoList todoList={todoList} index={index} setTodoList={setTodoList} />;
            })
        }
    </section>
);

这是 TodoList.js

function handleDeleteTodo(cardIndex) {
    setTodoList(index, prevTodoList => {
        const newTodoList = {...prevTodoList};
        newTodoList.cards.splice(cardIndex, 1);
        return {...newTodoList};
    });
}
return (
    <section className="body" ref={todosBodyRef} >
        {
            todoList.cards.map((todo, cardIndex) => {
                return <TodoItem listIndex={index} cardIndex={cardIndex} todo={todo} handleDeleteTodo={handleDeleteTodo} />
            })
        }
    </section>
);

这是 TodoItem.js

function deleteButtonOnClick() {
    handleDeleteTodo(cardIndex);
}
return (
    <>
        <p>{todo.name}</p>
        <div className="controls">
            <i className="far fa-trash-alt deleteCard" onClick={deleteButtonOnClick}></i>
        </div>
    </>
)

当我点击删除图标时,如果 TodoItem 是最后一个 TodoItem,它会完美删除,但如果它不是最后一个项目,它将删除接下来的 2 个 Todoitems 而不是自身。

我不知道我做错了什么。如果有人向我解释发生了什么,那就太好了:_(

编辑: 我在handleDeleteTodo添加了这个if语句:

if (newTodoList.cards == prevTodoList.cards) {
    console.log("True"); // It means both cards references are Same.
}

它记录为真。这意味着两张卡的引用是相同的,我也必须克隆它。

有没有办法在不克隆cards数组的情况下解决这个问题?因为我正在克隆整个 todoList 对象,我也不想克隆卡片。

【问题讨论】:

  • 为什么你在TodoListsetTodoList的调用中传递index而不是cardInex
  • 如何将 cardIndex 传递给 handleDeleteTodo?如果您传递了正确的索引值,请尝试使用filter 函数。
  • @k-wasilewski todoLists 是一个todoList 数组,它是一个包含namecards 的对象。 cards 是一组卡片。为了修改 todoList 我必须通过它的索引而不是卡片的索引来访问它
  • @Miraziz index 是当前的 TodoList 数组索引。我将它作为道具从App.js 传递给TodoList.js

标签: javascript reactjs react-hooks setstate react-state


【解决方案1】:

我发现了问题!

我使用了一个嵌套的 JS 对象,并使用扩展运算符克隆了它。 (这是一个浅拷贝,它不会克隆对象内部的对象!)

所以我使用了rfdc 并使用它深度克隆了我的对象。在 TodoList.js 中是这样的:

import clone from 'rfdc/default';
function handleDeleteTodo(cardIndex) {
    setTodoList(index, prevTodoList => {
        const newTodoList = clone(prevTodoList); // This is where cloning happens
        newTodoList.cards.splice(cardIndex, 1);
        return newTodoList;
    });
}

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2018-06-01
    • 2015-06-14
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多