是什么导致我的 Svelte 应用程序出现此 "cannot read property 'title' of undefined" 错误?

What causes this "cannot read property 'title' of undefined" bug in my Svelte app?

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

在 App.svelte 中,我导入 TodoItem 组件循环一个 todos 数组:

import TodoItem from './TodoItem.svelte';
//more code

{#each todos as t, index}<TodoItem />{/each}

TodoItem.svelte我有:

<script>
    import { createEventDispatcher } from 'svelte';
    export let index;
    export let t;
    export let id;
    export let title;
    export let completed;
    
    function deleteTodo(tid){
        let itemIdx = todos.findIndex(x => x.id == tid);
        todos.splice(itemIdx,1);
        todos = todos;
    }
    
    function editTodo(tid) {
        isEditMode = true;
        let itemIdx = todos.findIndex(x => x.id == tid);
        currentToDo = todos[itemIdx];
    }
    
    function completeTodo(tid){
        let itemIdx = todos.findIndex(x => x.id == tid);
        let todo = todos[itemIdx];
        todo.completed = !todo.completed;
        todos = todos;
    }
</script>

<tr>
    <td>{index + 1}</td>
    <td class="{t.completed == true ? 'completed' : ''}">{t.title}</td>
    <td class="text-center"><input type="checkbox" checked="{t.completed}" on:change={completeTodo(t.id)}></td>
    <td class="text-right">
        <div class="btn-group">
            <button on:click="{() => editTodo(t.id)}" class="btn btn-sm btn-primary">Edit</button>
            <button on:click="{deleteTodo(t.id)}" class="btn btn-sm btn-danger">Delete</button>
        </div>
    </td>
</tr>

由于我没有弄清楚的原因,我在该组件中遇到 Cannot read property 'title' of undefined 错误,如 REPL 所示。

我做错了什么?

错误“cannot read something of thing”意味着您正在尝试访问名为“thing”的变量的属性“something”。
所以在你的情况下.. “无法读取未定义的 属性 标题”意味着您正在尝试访问未定义的内容的 属性“标题”。
在您的代码中,我只能看到一个 object,您正在尝试访问 属性“标题”。
t.title.
所以错误是说 t 变量没有定义。
您违规的代码行是:
{#each todos as t, index}<TodoItem />{/each}.
因为您没有将 TodoItem 发送给它期望的 t 变量。
将其更改为:
{#each todos as t, index}<TodoItem t/>{/each}