在 Stenciljs 中每分钟调用一次函数

Call function every minute in Stenciljs

是否可以在 Stenciljs 组件中每分钟调用一个函数。 我想基本上这样做:

  setInterval(() => { this.checkSomeStuff() }, 60000);

但问题是Stenciljs无法处理。不能像那样设置功能。我应该使用@Method、@Event、@Listen 还是其他什么?

您可以在其中一个组件生命周期中设置时间间隔,例如。 G。 componentWillLoad:

@Component({ tag: 'my-comp' })
export class MyComp {
  interval: any;

  componentWillLoad() {
    this.interval = setInterval(() => { this.checkSomeStuff() }, 60000);
  }

  componentDidUnload() {
    clearInterval(this.interval);
  }

  checkSomeStuff() {
    // ...
  }

  render() {
    return <Host />;
  }
}

生命周期方法的完整列表:https://stenciljs.com/docs/component-lifecycle

这可能是一个棘手的问题,但这取决于您想要实现的目标。

Simon Hänisch 已经完美地指出了您可以使用组件的生命周期方法。 componentWillLoad 开始间隔,componentDidUnload 将是一个不错的选择。

但请注意,Stenciljs 仅在必要时才渲染您的组件。这也意味着当 Stencil "thinks" 不再需要它们时,它们将被删除。比起你的组件的整个代码就像被删除一样,这当然也会停止你的 setInterval。

当你有 60 秒的间隔时,我可以想象用户可能会滚动或做一些其他可能会卸载你的组件的事情,当用户返回到你的组件时,间隔再次从零开始。 (这就是为什么我一开始就说 可能很棘手 因为在某些情况下这种行为在某些情况下是好的)。

如果不是 - 您可能需要存储您的间隔,而不是从它停止的地方开始。为此,也许静态变量就足够了。

但也许最好的方法是使用 @Method 装饰器。

  @Method()
  checkSomeStuff() {
    // check stuff
  }

这使得组件的方法全局可用,您可以在 index.html 中调用它,例如像这样:

index.html

<your-component id="comp"></your-component>
<script>
  document.getElementById("comp").checkSomeStuff(); // yes you can call the function in that way
</script>

这使您可以 运行 index.html 中的 SetInterval。

@Christian Meyer 说的有道理。有从组件外部或内部更新它的选项。我强烈建议做外面的方式。 我唯一可以添加的是不要忘记所有被推荐为 Promise 的方法: https://stenciljs.com/docs/methods

import { Method } from '@stencil/core';

export class TodoList {

  @Method()
  async showPrompt() {
    // show a prompt
  }
}
(async () => {
  await customElements.whenDefined('todo-list');
  const todoListElement = document.querySelector('todo-list');
  await todoListElement.showPrompt();
})();

也考虑一种基于数据绑定的更新方式。