为什么 Codesandbox.io 上的 Svelte 应用会导致 TypeError ... is not a constructor?
Why does Svelte app on Codesandbox.io result in TypeError ... is not a constructor?
试图了解可写和可读存储在 Svelte 中的工作原理。因此尝试在 codesandbox.io.
中重现 https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores 中描述的警报组件的最小版本
但是,我收到一个错误:TypeError _Alert.Alert 不是构造函数
codesandbox代码在https://codesandbox.io/s/error-Whosebug-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!");
任何人都可以看到可能导致错误的原因。
看来您需要继续学习本教程,您仍在使用样板 subscribe/unsubscribe 方法,自 auto-subscribe 存在以来,该方法从未在 Svelte 应用程序中使用过。
您当前收到错误的原因是 App.svelte 中的这一行 import { Alert } from "./Alert.svelte";
。
当您在 Svelte 中导入组件时,您不会将名称括在方括号中。这应该是 import Alert from "./Alert.svelte";
然后你在你的标记中像这样使用它 <Alert />
。
试图了解可写和可读存储在 Svelte 中的工作原理。因此尝试在 codesandbox.io.
中重现 https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores 中描述的警报组件的最小版本但是,我收到一个错误:TypeError _Alert.Alert 不是构造函数
codesandbox代码在https://codesandbox.io/s/error-Whosebug-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!");
任何人都可以看到可能导致错误的原因。
看来您需要继续学习本教程,您仍在使用样板 subscribe/unsubscribe 方法,自 auto-subscribe 存在以来,该方法从未在 Svelte 应用程序中使用过。
您当前收到错误的原因是 App.svelte 中的这一行 import { Alert } from "./Alert.svelte";
。
当您在 Svelte 中导入组件时,您不会将名称括在方括号中。这应该是 import Alert from "./Alert.svelte";
然后你在你的标记中像这样使用它 <Alert />
。