簡體   English   中英

Svelte 在編輯后不打印數組元素

[英]Svelte not printing array elements after they're edited

嘿,我在學習 svelte 時遇到了這個問題,我用我對 svelte 的簡單知識制作了這個 todo 應用程序。 問題是我添加了待辦事項,它們被添加了。 我刪除待辦事項,它們被刪除。 但是,當我刪除多個待辦事項並嘗試插入一個新的待辦事項時,它不會將待辦事項打印到 HTML 並給出錯誤消息:

錯誤:未捕獲(承諾中):無法讀取 null 的屬性(正在讀取“removeChild”)

代碼:

<script>


  let todos = []
  let heading = 'Enter heading here';
  let msg = 'enter your todo here'
  let n = 1;
  function pushTodo(){
    todos = [...todos, new Todo(n, heading, msg)]
    n+=1
        // Logged todos and n for debugging purposes
        console.log('added todo and increased n to'+ n)
        console.log(todos)
  }

  class Todo{
    constructor(id, title, msg){
      this.id = id
      this.title = title
      this.msg = msg
    }
  }

  function deleteTodo(id) {
    todos.splice(id-1, 1);
    document.getElementById(id).remove();
        // Logged the todo array for debugging purposes
    console.log(todos)
  }
</script>

<input type="text" bind:value={heading}>
<input type="text" bind:value={msg}>

<button on:click={pushTodo}>insert todo</button>

{#each todos as {id, title, msg}}
<div id= {id.toString()}>
<h6>{id}</h6>
<h2>{title}</h2>
<h4>{msg}</h4>
<button on:click={()=>{deleteTodo(id)}}>delete</button>
</div>
 
{/each}

您可能不應該自己刪除 HTML 元素,svelte 會為您做到這一點。 問題是,當您調用todos.splice時,svelte 不會意識到todos的內容發生了變化。 你需要分配todos來實現這一點。 嘗試這個:

  function deleteTodo(id) {
    // find the index of the element to remove
    const index = todos.findIndex(todo => todo.id === id);
    todos.splice(index, 1);
    // important: assign todos to itself
    // that way svelte realizes that the content of todos has changed!
    todos = todos;
        // Logged the todo array for debugging purposes
    console.log(todos)
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM