Svelte 3,异步onMount还是有效的替代方案? [英] Svelte 3, async onMount or a valid alternative?
问题描述
我需要在Svelte onMount()
中使用async-await
.
What I need is to use async-await
in Svelte onMount()
.
或者也许您可以建议我哪里错了,以及我可以选择使用什么.
要复制
- 转到此处: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version= 3.23.0
- 打开控制台
- 单击按钮
- 您应该看到以下消息:
"Mounting..."
和"A lot of background work..."
- 如果再次单击,则不会写入销毁消息
- go here: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version=3.23.0
- open the console
- click on the button
- you should see messages:
"Mounting..."
and"A lot of background work..."
- 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屋!