为什么“渲染”不以更新状态重新渲染UI?

时间:2019-04-25 02:29:36

标签: javascript

我正在研究模块和类,并创建了继承 Component 类的Component类和 App 类。我的渲染方法在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方法。这似乎是一个好方法吗?

1 个答案:

答案 0 :(得分:0)

发现错误:

更改了初始化:

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

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