为什么Codesandbox.io上的Svelte应用程序会导致TypeError..不是构造函数吗



试图了解可写和可读存储在Svelte中是如何工作的。因此,尝试复制中描述的警报组件的最小版本https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores位于codesandbox.io.

但是,我收到一个错误:TypeError_Alert。Alert不是构造函数

codesandbox代码位于https://codesandbox.io/s/error-stackoverflow-tour1?file=/App.svelte

以下是相关文件的内容:

index.js

import App from "./App.svelte";
const app = new App({
target: document.body
});
export default app;

App.svelte

<script>
import { Alert } from "./Alert.svelte";
</script>
<main>
<Alert />
</main>

Alert.svelte

<script>
import { alertStore } from "./stores.js";
import { onDestroy } from "svelte";
let alertContent = "";
const unsubscribe = alertStore.subscribe(value => (alertContent = value));
onDestroy(unsubscribe);
</script>
{#if alertContent}
<div on:click={() => alertContent = ""}>
<p> {alertContent} </p>
</div>
{/if}

stores.js

import { writable } from "svelte/store";
export const alertStore = writable("Welcome to the to-do list app!");

有人能看到是什么原因导致了这个错误吗。

看起来你需要继续学习教程,你仍然在使用样板订阅/取消订阅方法,这在Svelte应用程序中从未使用过,因为存在自动订阅。

当前出现错误的原因是App.svelte.中的import { Alert } from "./Alert.svelte";

在Svelte中导入组件时,不会将名称括在括号中。这应该是import Alert from "./Alert.svelte";,然后在标记中像这样使用<Alert />

最新更新