【问题标题】:Svelte, removing elements苗条,去除元素
【发布时间】:2021-02-13 06:28:20
【问题描述】:

Svelte 的新手要温柔!

我遵循了一些教程示例,使用每个块创建项目列表,然后删除项目,但它们都使用数组作为数据存储,然后使用拼接/切片等来删除像 at 这样的项目;

https://svelte.dev/tutorial/keyed-each-blocks

我正在尝试使用来自异步 json 占位符请求的 JSON 数据存储来实现类似的事情。

这是我目前所拥有的 https://svelte.dev/repl/9d1bc0a8af79459f8ad0cd6c9cb82fa2?version=3.29.4

非常欢迎任何建议和帮助。谢谢

【问题讨论】:

    标签: svelte


    【解决方案1】:

    您所做的实际上不是从承诺中返回数据,而只是返回成功状态,即您将数据本身保存到单独的变量中:

    let things = []
    
    async function getThings(){
      const res = await fetch(`https://jsonplaceholder.typicode.com/users`);
      const json = await res.json();
    
      if (res.ok) {
        // save the result to json
        things = json;
        // you can even leave this part out
        return true;
      } else {
        throw new Error(text);
      }
    }
    

    那么当 promise 解决时,你当然会循环遍历数组:

    {#await promise}
        <p>...waiting</p>
    {:then success}
      {#each things as thing, index (thing.id)}
        stuff goes here
      {/each}
    {/await}
    

    最后在你的删除函数中你现在可以操作数组了:

    function onDelete(id) {
        things = things.filter(t => t.id != id)
    }
    

    另一种方法是将获取数据与显示数据分开,使其成为两个不同的组件:

    {#await promise}
        <p>...waiting</p>
    {:then things}
      <DisplayComponent data={things} />
    {/await}
    

    DisplayComponent 内部,您的数据现在将位于一个常规数组中,您可以对它做任何您想做的事情。这样做的一个好处是您可以通过发送模拟数据来独立测试DisplayComponent

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-30
      • 2020-03-13
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多