【问题标题】:How can I get the access of a const inside my function?如何在我的函数中访问 c​​onst?
【发布时间】:2022-01-25 07:02:30
【问题描述】:

如何授予对要在函数内部使用的 const 的访问权限?在这种情况下,我想在我的函数 fetchListings 中访问我的 const catName。我收到此错误:

问题更新:

ReferenceError: catName is not defined

<script context="module">

const fetchListings = async () => {

        try {
            // get reference to listings collection
            const listingsRef = collection(db, 'listings');
            // create a query to get all listings
            const q = query(
                listingsRef,
                where('type', '==', catName),
                orderBy(timestamp, 'desc'),
                limit(10)
            );
            // execute query
            const querySnap = await getDocs(q);

            let lists = [];

            querySnap.forEach((doc) => {
                console.log(doc);
            });

        } catch (error) {
            console.log(error);
        }
    };
    fetchListings();
</script>

<script>
    import { page } from '$app/stores';
    // export the const catName to the function above
    export const catName = $page.params.catName;
</script>

Hi {catName}!

【问题讨论】:

  • 您可能打算使用where('type', '==', catName), 而不是where(type, '==', catName),
  • 谢谢,现在我得到了正确的错误:ReferenceError: catName is not defined
  • fetchListings的模块是否导入了定义catName的模块?
  • fetchListings(catName) ?我在考虑范围问题?

标签: javascript svelte sveltekit


【解决方案1】:

您遇到的问题来自&lt;script context="module"&gt; 的工作方式。

模块级脚本标记用作每个应用程序一次的设置脚本。这意味着它只会运行一次,当您的应用程序初始化时,它将在任何常规 &lt;script&gt; 标记代码运行之前运行。见:https://svelte.dev/docs#component-format-script-context-module

这意味着&lt;script context="module"&gt; 将无法访问在普通&lt;script&gt; 标签代码中定义或创建的内容。因此,您的常量的not defined 错误,在常规&lt;script&gt; 标记中定义。

基于此,您的代码需要重构(重组)。我的理解是您将fetchListings 放在模块上下文中,因为您想预取结果并且只在应用启动期间执行一次。

要实现这一点,您可以像这样重构代码:

<script context="module">
  let preFetched=false
</script>

<script>
  import { page } from '$app/stores';

  // export is not needed
  const catName = $page.params.catName;  

  async function fetchListings() => {
    // Your code  ...
  } 
  if(!preFetched){
    fetchListings()
    preFetched=true
  }

</script>

Hi {catName }!

这确保fetchListings 函数只运行一次。诀窍是模块上下文中定义的变量、常量等可以被该模型的所有实例访问。所以当第一个实例被创建时,它将运行fetchListings函数,并将preFetched变量设置为false,所以后续实例不会这样做。

这只是一种可能的方法。根据您想要完成的具体内容,您可能希望以不同的方式组织事物。但是,在了解了 &lt;script context="module"&gt; 的作用和运行时间后,您应该能够提出最适合您需求的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 2012-01-08
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多