为什么“渲染”不会重新呈现具有更新状态的UI?

问题描述 投票:1回答:1

我正在玩模块和类,我创建了继承Component类的Component类和App类。我的render方法是在Component类中。当我“removeItem”时,我可以记录并看到我的“this.state”已更改,但之后,我调用“this.render()”,它被调用,但它不会用我的新“this.state”重新渲染只有一个项目。这是为什么?我怎样才能使它工作?

document.componentRegistry = {}

class Component {
  constructor(wrapper, props) {
    this._id = Math.random()
    document.componentRegistry[this._id] = this
    this.wrapper = wrapper
    if (props) {
      this.props = props
    }
  }

  render() {}
  onMount() {}

  init() {
    this.wrapper.insertAdjacentHTML('beforeend', this.render())
    this.onMount()
  }

  update() {
    this.wrapper.textContent = ''
    this.wrapper.insertAdjacentHTML('beforeend', this.render())
  }
}

class App extends Component {
  constructor(...args) {
    super(...args)
    this.state = {
      items: [{ name: 'name-1', id: 1 }, { name: 'name-2', id: 2 }]
    }
    this.init()
  }
  render() {
    return `<div class="some-class" id="someId" >
                <ul>${this.state.items
                  .map(({ name, id }) => {
                    return `<li id=${id} class='list-item' onclick="document.componentRegistry[${
                      this._id
                    }].removeItem(this)">${name}</li>`
                  })
                  .join('')}
                </ul>
             </div>`
  }

  removeItem(element) {
    const elId = parseInt(element.id)
    this.state = { items: this.state.items.filter(item => item.id !== elId) }
    this.update()
  }

  onMount() {
    alert('App is successfully mounted!')
  }
}

UPDATE

我在父类上添加了update方法。这似乎是一个好方法吗?

javascript
1个回答
0
投票

发现了这个bug:

改变初始化:

  init() {
    this.wrapper.textContent = ''
    this.wrapper.insertAdjacentHTML('beforeend', this.render())
    this.onMount()
  }

并在更新后调用它而不是渲染

© www.soinside.com 2019 - 2024. All rights reserved.