如何触发/强制更新 Svelte 组件 [英] How to trigger/force update a Svelte component
问题描述
我正在努力了解 svelte 3 反应性的东西...
I am trying to get my head around the svelte 3 reactivity thing...
我想在单击按钮时强制刷新 UI.我正在使用一个自定义组件
AsyncFetcher
,它接受 HTTP 发布数据,并为其插槽返回data
对象(http 发布结果).
I wanted to force refreshing a UI on a button click. I am using a custom component
AsyncFetcher
that accepts HTTP post data, and returnsdata
object (http post result) for its slot.
我想要禁用功能.因此,当单击禁用"按钮时,将调用 http api,然后刷新数据视图.
I wanted to have a disable functionality. So when the "Disable" button is clicked an http api is called followed by a refresh of the data view.
<script>
export let id
function onDisable() {
fetch('disable-api-url', {id: id})
// Then ??
// What to do after the fetch call, to refresh the view
}
</script>
<AsyncFetcher postParam={id} let:data>
{data.name}
<button on:click={??}>Refresh</button>
<button on:click={onDisable}>Disable Item</button>
</AsyncFetcher>
我试着做 on:click={() =>id=id}
欺骗它刷新无济于事.如果 id
是一个对象而不是字符串 id={...id}
会起作用,不幸的是,这里不是这种情况.
I tried doing on:click={() => id=id}
to trick it to refresh to no avail. If id
would have been an object rather than string id={...id}
would have worked, which unfortunately, is not the case here.
实现这一目标的正确方法是什么?
What would be a correct way to achieve this?
推荐答案
使用组件来管理获取是非常非常规的.通常,您会在 onMount
内或在事件处理程序中获取数据:
Using a component to manage fetches is very unconventional. Typically you'd fetch data inside onMount
, or in an event handler:
<script>
import { onMount } from 'svelte';
let initialData;
let otherData;
onMount(async () => {
const res = await fetch('some-url');
initialData = await res.json();
});
async function update() {
const res = await fetch('some-other-url');
otherData = await res.json();
}
</script>
{#if initialData}
<p>the data is {initialData.something}</p>
{/if}
<button on:click={update}>update</button>
这篇关于如何触发/强制更新 Svelte 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!