【问题标题】:What causes this component was created without expected prop error in my Svelte app?是什么原因导致在我的 Svelte 应用程序中创建此组件时没有预期的 prop 错误?
【发布时间】:2021-01-19 10:47:06
【问题描述】:

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

在 App.svelte 中,我将 TodoItem 组件循环导入 todosarray:

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

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

TodoItem.svelte 我有:

<script>
    import { createEventDispatcher } from 'svelte';
    export let index;
    export let t;
    export let id;
    export let title;
    export let completed;
    
    //more code here
</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>

在控制台中,我收到类似 "&lt;TodoItem&gt; was created without expected prop 'index'" 的错误,正如 REPL 所示。

更新

我将{#each todos as t, index}&lt;TodoItem t/&gt;{/each} 替换为{#each todos as t, index}&lt;TodoItem t index={index} id={t.id} title={t.title} completed=false /&gt;{/each},但标题仍为undefined

缺少什么?

【问题讨论】:

  • t 从您的组件调用更改为 t={t},但我不知道为什么...您不需要提供 idtitle 等,因为您已经将整个对象 t 提供给组件,因此在组件内部,您可以使用 t.idt.title 访问对象的属性
  • 对不起,我犯了一个错误。定义组件属性的简写代码是{t},而您的代码是t。这就是为什么 t 没有在你的组件中定义的原因。

标签: svelte svelte-3 svelte-component svelte-2


【解决方案1】:

您没有提供index 作为组件的道具。将您的组件调用更改为&lt;Todoitem {t} {index}/&gt; 或将export let index 更改为let index,则组件不需要索引属性。
编辑:修复了速记代码以更正那些,即。 {t}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多