如何在javascript中改变属性值时重置所有状态?

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

我使用的是模板框架,在我的组件中,我使用不同的状态来触发不同的事件。在我的组件中,我使用不同的状态来触发不同的事件。我也从javascript中更新了组件的属性值。

我想重置所有状态值,然后用更新的属性值重新加载组件。新的属性值负责许多操作,如调用api,生成缓存键等。

谁能给我一个最好的方法来满足我的要求。目前我是在属性的watcher方法中重置所有状态,然后调用componentWillLoad事件,但是我在这个方法中遇到了很多问题。

示例代码

@Prop() symbol!: string;
  @Watch('symbol')
  symbolChanged(newSymbol: string, prevSymbol: string) {
    if (newSymbol && newSymbol !== prevSymbol) {
      this.resetStates();
    }
  }
  resetStates() {
   //Reset all state values here
    this.componentWillLoad();
  }
stenciljs
1个回答
1
投票

通过在渲染方法的根元素上设置key属性可以解决我的问题,就像下面的代码片段。

 uniqKeyId = uniqid.get();

 @Prop() symbol!: string;
    @Watch('symbol')
    sysmbolWatcher(newSymbol: string, prevSysmbol: string) {
    if (newSymbol != prevSysmbol) {
       //update key attribute each switch of exchange
       this.uniqKeyId = uniqid.get();
       //Set default values based on properties as to consider this as fresh request.
       this.setDefaultValues();
    }
  }

在渲染方法中,如下图所示

 render() {    
      return (    
        <section class="cid-minichart" key={this.uniqKeyId}>
            //Render markup
        </section>
      );
  }
© www.soinside.com 2019 - 2024. All rights reserved.