【问题标题】:Svelte todo app bug: new todos id property is never greater than 2Svelte todo 应用程序错误:新的 todos id 属性永远不会大于 2
【发布时间】:2020-06-30 23:25:29
【问题描述】:

我正在 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>

由于某种原因,我无法找到 - 我的 todos 的最大 id 是 2 - 我添加了多少不计。

查看 REPL here

我的错误在哪里?

【问题讨论】:

  • 可能是笔误,但其实很简单:todos[todos.length - 1].id,也就是列表中last的id,总是返回1,因为你@ 987654325@新的待办事项。只需使用第一个:todos[0].id + 1,它就会随心所欲地工作。
  • 更准确地说,我说的是您演示中的第 22 行。

标签: javascript svelte svelte-3


【解决方案1】:

改变

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

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

因为你的第一个 todos 有最大的 id,而不是最后一个。

【讨论】:

    【解决方案2】:

    对我来说似乎复杂而脆弱,为什么不记住最后一个插入 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() 而不是只是不倒车并推入名单?

    【讨论】:

    • 我需要分配并递增 if 到 todos。我还需要先显示它们最新的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2019-12-27
    • 2020-05-06
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多