如何从帮助程序脚本导入的变量更改上重新呈现组件?

问题描述

我有类似下面的代码,我想和您一起检查是否有更好的方法。基本上,我有一个从第三方API获取数据的帮助程序脚本。我希望每次调用API时都会重新导入导入此辅助脚本的组件。该API被多次调用

我现在正在这样做:

MyClass脚本:

import { rerenderComponentList } from '../../../helpers/myscript';

export default class MyClass extends LitElement {
  static get properties() {
    return {
      item: {},};
  }

  constructor() {
    super();
    this.item = [];

    rerenderComponentList(this);
  }

  render() {
    const icon = Iconify.renderSVG(this.item.icon,{});

    return html` <div>Hello</div> `;
  }

  static get styles() {
    return styles;
  }
}

导入的rerenderComponentList函数用于将当前元素对象发送到帮助脚本。

助手脚本:

const list = [];

export function rerenderComponentList(object) {
  list.push(object);
}

function rerenderComponent() {
  list.map((item) => item.requestUpdate());
}

function callbackIcons(loaded) {
  if (loaded.length) {
    rerenderComponent();
  }
}

//Function used to call API in app.js
export function loadIcons(icons) {
  API.myfunction(icons,callbackIcons);
}

rerenderComponent函数用于在每个元素对象上调用requestUpdate

任何更好和更好的建议将不胜感激!

解决方法

这是新的 ReactiveController 可以提供帮助的地方。这让您可以连接到组件生命周期,以便您的 API 可以告诉 LitElement 何时需要呈现:

import { ReactiveController,ReactiveControllerHost } from 'lit';

export class MyController 
    implements ReactiveController {

    list = [];

    constructor(private host: ReactiveControllerHost) {
        host.addController(this);
    }

    private callbackIcons(loaded) {
        this.list = loaded;
        this.host.requestUpdate();
    }
    
    loadIcons(icons) {
        API.myfunction(icons,items => this.callbackIcons(items));
    }
}

然后在您的元素中:

import { LitElement,html } from 'lit';
import { customElement } from 'lit/decorators.js';
import { MyController } from './my-controller.js';

@customElement('my-element')
class MyElement 
    extends LitElement {

    private myController = new MyController(this);

    render() {
        const icons = this.myController.list.map(i => Iconify.renderSVG(i)) ;
        return html`... ${icons} ...`;
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...