You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SolidJS资源Fetcher延迟调用及Switch分支误触发问题解决

问题1:如何推迟SolidJS中resource的fetcher函数调用?

要推迟createResource的fetcher执行,核心是通过source依赖信号控制触发时机:

  • 初始化时给source设置一个无效值(如null/undefined),此时fetcher不会执行
  • 当需要发起请求时,再将source更新为有效参数

示例代码:

import { createResource, createSignal } from 'solid-js';

// 初始source为null,fetcher暂不执行
const [fetchId, setFetchId] = createSignal<string | null>(null);
const [data] = createResource(fetchId, (id) => api.fetchTargetData(id));

// 触发请求的时机(比如按钮点击)
const triggerFetch = () => setFetchId('target-resource-id');

如果使用SolidJS 1.6+,deferStream: true选项可以推迟流数据的处理,但核心触发逻辑仍需通过source控制。

问题2:为何mappings资源会在Switch的false分支被调用?该如何避免?

原因

createResource的fetcher会在组件初始化阶段执行,只要其source函数返回有效参数(比如你的代码中params.id存在),就会立即发起请求,和组件是否渲染到DOM(Switch分支是否匹配)无关。

解决方法

将mappings的source与pipeline的状态绑定,仅当pipeline状态满足条件时,source才返回有效参数,否则返回null/undefined,从而阻止fetcher提前执行。

修改后的代码:

const [pipeline] = createResource(() => api.pipeline(params.id));
// 仅当pipeline状态非INCOMPLETE时,才返回params.id作为source
const [mappings] = createResource(() => {
  const pipe = pipeline();
  return pipe?.state !== PipelineState.INCOMPLETE ? params.id : null;
}, { deferStream: true });

<Switch>
  <Match when={pipeline()?.state == PipelineState.INCOMPLETE}>
    <div class="flex flex-col items-center py-12 px-4 sm:px-6">
      <h1 class="text-medium mb-2 text-2xl text-neutral-600">No mappings</h1>
      <p class="text-neutral-600">Nothing to show until pipeline is fully configured.</p>
    </div>
  </Match>
  <Match when={pipeline()?.state != PipelineState.INCOMPLETE}>
    <Show when={mappings() != undefined} fallback={<LoadingIcon/>}>
      {/* 渲染mappings内容 */}
    </Show>
  </Match>
</Switch>

当pipeline状态为INCOMPLETE时,mappings的source返回null,fetcher不会触发;状态切换后,source返回有效ID,才会发起api.pipelineMappings请求。


内容的提问来源于stack exchange,提问作者expert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:07:13