javascript - 在 React 中删除集合项 - map 与 for 循环

标签 javascript reactjs

我正在 React 中创建简单的待办事项应用程序。 最后我在修修补补,想通过各种方式达到相同的结果。

当我在 render 中使用 map 方法填充数组时,一切都很好:

const todosItems = this.state.todos.map((todo) =>
  <TodoItem name={todo.text} key={todo.id} onClick={(e) => this.deleteButtonClick(todo.id)} />
);

当我用 for 循环做同样的事情时:

const todosItems = [];
const todos = this.state.todos;
for (let i = 0; i < todos.length; i++) {
  todosItems.push(<TodoItem name={todos[i].text} key={todos[i].id} onClick={(e) => this.deleteButtonClick(todos[i].id)} />);
}

当我删除其中一项时应用崩溃:

[Error] TypeError: undefined is not an object (evaluating 'todos[i].text')
_loop (index.js:17650)
render (index.js:17659)
finishClassComponent (index.js:5285:149)
performUnitOfWork (index.js:5931:360)
workLoop (index.js:5938)
callCallback (index.js:2613:108)
dispatchEvent
invokeGuardedCallbackDev (index.js:2633)
invokeGuardedCallback (index.js:2649:791)
replayUnitOfWork (index.js:5800:88)
renderRoot (index.js:5960:160)
performWorkOnRoot (index.js:6151)
performWork (index.js:6133:813)
performSyncWork (index.js:6131:155)
interactiveUpdates$1 (index.js:6184:488)
dispatchInteractiveEvent (index.js:3758:115)
dispatchInteractiveEvent

完整代码:https://github.com/ArturKot95/todo-react/blob/master/index.js

预先感谢您的帮助。

编辑: 感谢您提供解决方案:D。在学习 React 时对我来说最重要的是认为状态就像程序中的快照一样,不能直接影响组件的状态,而是作用于副本。

delete 替换为 Array.prototype.filter:

deleteButtonClick = (id) => {
    let todos = this.state.todos.slice();
    todos = todos.filter(todo => todo.id !== id);

    this.setState({
        todos: todos
    });
}

const todos = this.state.todos 替换为 const todos = this.state.todos.slice()

最佳答案

delete 运算符导致错误

When you use delete operator to remove an array element, the array length is not affected.

deleting array elements

这意味着如果数组有三个待办事项 [{todo}, {todo}, {todo}]

当你删除第二个元素时:delete todos[1]

待办事项将更改为:[{todo}, empty, {todo}]

如你所见,数组的长度仍然是三,所以错误发生在for语句中。

为什么 map 有效:

Map callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

map description

PS:检查错误时,可以添加一些日志来检查发生的时间。 :D

关于javascript - 在 React 中删除集合项 - map 与 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634298/

相关文章:

javascript - 如何在 AngularJS 中单击按钮时获取所选值?

reactjs - 当使用 useState 钩子(Hook)更改 props 时,组件不会重新渲染

javascript - 如何隐藏嵌入的javascript key ?

javascript - 如何在 Javascript 中从 dayjs() 导出插件?

javascript - 更新表单中的数据。保持可编辑状态。 (与 Redux react ,无 redux-form)

javascript - Webpack、React JSX、Babel : Module build failed, "unexpected token"为空?

javascript - 无法在 reactjs 中使用 map 显示列表项?

javascript - Mongoose 的意外行为

javascript - NodeRed服务器: Install custom nodes while running

javascript - 使用 jquery 重置 html 元素