问题
I am working on a small ToDo application in Svelte for learning purposes (Im new to Svelte).
I have this code for adding a new todo:
<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>
For a reason I was unable to find - the maximum id of my todos is 2 - no meter how many I add.
See the REPL here.
Where is my mistake?
回答1:
Seems complicated and brittle to me, why not just remember the last insert 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;
}
// ...
Also why unshift()
and reverse()
instead of just not reversing and pushing onto the list?
回答2:
change
newTodo.id = todos[todos.length - 1].id + 1;
to
newTodo.id = todos[0].id + 1;
since your first todos have the greatest id, not the last.
来源:https://stackoverflow.com/questions/62659747/svelte-todo-app-bug-new-todos-id-property-is-never-greater-than-2