我怎样才能在我的函数中获得对 const 的访问?

How can I get the access of a const inside my function?

如何授予对要在函数内部使用的常量的访问权限?在这种情况下,我想在我的函数 fetchListings 中访问我的常量 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}!

您 运行 遇到的问题来自 <script context="module"> 的工作原理。

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

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

基于此,您的代码将需要重构(重组)。我的理解是,您将 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,因此后续实例将不会这样做。

这只是一种可行的方法。根据您想要完成的具体目标,您可能希望以不同的方式组织事情。但是,了解了 <script context="module"> 的作用以及 运行 的作用后,您应该能够提出最适合您需求的解决方案。