Svelte todo 应用程序错误:新的 todos id 属性 永远不会大于 2

Svelte todo app bug: new todos id property is never greater than 2

出于学习目的,我正在使用 Svelte 开发一个小型 ToDo 应用程序(我是 Svelte 的新手)。

我有用于添加新待办事项的代码:

<script>
    import { onMount } from "svelte";
      
    let todos = [];
      
    onMount(async function() {
        todos.reverse();
    });
      
    function addTodo() {
        //Empty todo object
        let newTodo = {};
      
        //Set new todo object's properties (id, title, completed)
        if (todos.length == 0) {
            newTodo.id = 1;
        } else {
            newTodo.id = todos[todos.length - 1].id + 1;
        }
        newTodo.title = document.querySelector('#new_todo').value;
        newTodo.completed = false;
      
        //Add new todo at the beginning of the array
        todos.unshift(newTodo);
      
        todos = todos;
    }
</script>

<div class="input-group p-2">
    <input type="text" class="form-control" id="new_todo">
    <div class="input-group-append">
        <button on:click="{addTodo}" class="btn btn-sm btn-success">Add</button>
    </div>
</div>

由于某种原因我无法找到 - 我的待办事项的最大 ID 是 2 - 不知道我添加了多少。

查看 REPL here

我的错误在哪里?

对我来说似乎又复杂又脆弱,为什么不只记住最后插入的 ID?

// ...
    
let todos = [];
let lastInsertId = 0;
    
function addTodo(){
    //Empty todo object
    let newTodo = {};
        
    //Set new todo object's properties (id, title, completed)
    newTodo.id = ++lastInsertId;
    newTodo.title = document.querySelector('#new_todo').value;
    newTodo.completed = false;
        
    //Add new todo at the behining
    todos.unshift(newTodo);
    todos = todos;
}

// ...

另外,为什么 unshift()reverse() 而不是不反转并推入列表?

改变

newTodo.id = todos[todos.length - 1].id + 1;

newTodo.id = todos[0].id + 1;

因为您的第一个待办事项具有最大的 ID,而不是最后一个。