Svelte 3,异步onMount还是有效的替代方案? [英] Svelte 3, async onMount or a valid alternative?

查看:195
本文介绍了Svelte 3,异步onMount还是有效的替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Svelte onMount()中使用async-await.

What I need is to use async-await in Svelte onMount().

或者也许您可以建议我哪里错了,以及我可以选择使用什么.

要复制

  1. 转到此处: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version= 3.23.0
  2. 打开控制台
  3. 单击按钮
  4. 您应该看到以下消息:"Mounting...""A lot of background work..."
  5. 如果再次单击,则不会写入销毁消息
  1. go here: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version=3.23.0
  2. open the console
  3. click on the button
  4. you should see messages: "Mounting..." and "A lot of background work..."
  5. if you click again the destroy message is not written

为什么?

onMount()是否识别async功能承诺?应该吗?

Did onMount() recognizes the async function promise? Should it?

我需要async的行为,因为我需要在渲染Child组件之前等待function lazyLoading().

I need that async behavior because I need to wait for function lazyLoading() before rendering the Child component.

在Svelte中还有另一种方法吗?

推荐答案

仅说明为什么onMount不能成为async函数(此可能将来会改变,但不要这样做).没想到):

Just to explain why onMount can't be an async function (this might change in future, but don't expect it to):

您可以从onMount处理程序中返回一个函数,该函数在销毁组件时被调用.但是async函数只能返回承诺.由于promise不是函数,Svelte将忽略返回值.

You can return a function from an onMount handler that is called when the component is destroyed. But async functions can only return a promise. Since a promise isn't a function, Svelte will ignore the return value.

这与React中的useEffect相同,顺便说一句-该函数必须是同步的,以避免出现竞争情况.对于onMount的推荐解决方案与对于useEffect的解决方案相同—将async函数放入处理程序内

This is the same as useEffect in React, incidentally — the function must be synchronous in order to avoid race conditions. The recommended solution for onMount is the same as for useEffect — place an async function inside the handler:

onMount(() => {
  async function foo() {
    bar = await baz();
  }

  foo();

  return () => console.log('destroyed');
});

(请注意,尽管在销毁的组件中分配状态是无害的,但您有责任处理在诺言解决之前,由于销毁组件而导致的任何竞争条件.)

(Note that you're responsible for handling any race conditions that arise as a result of the component being destroyed before the promise resolves, though assigning state inside a destroyed component is harmless.)

我已经开始讨论一个问题,以在这些情况下提供更多有用的反馈: https://github.com/sveltejs/svelte/issues/4944

I've opened an issue to discuss providing more useful feedback in these situations: https://github.com/sveltejs/svelte/issues/4944

这篇关于Svelte 3,异步onMount还是有效的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆