你如何看待国家财产取决于另一个属性(来自同一类)?

时间:2017-08-31 20:29:50

标签: javascript reactjs

我想知道如何处理依赖于另一个属性的组件状态中的属性,例如:

class Sample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mainProperty: 1,
      something: {
        dependingOnMainProperty: `foo${this.state.mainProperty}bar`
      }
    }
  }
}

基本上,当我将dependingOnMainProperty更改为mainProperty时,我希望setState自动更新。我应该为此编写一个函数还是有其他解决方案?

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式使用getter和setter;



class Component {
  constructor(...props){
    props.forEach(prop => this[prop] = "whatever");
  }
}

class Sample extends Component {
  constructor(...props) {
    super(...props);
    this.state = {
      something: {
        __mp__: "tester",
        dependingOnMainProperty: `foo${this.mainProperty}bar`,
        get mainProperty(){
          return this.__mp__;
        },
        set mainProperty(v){
          this.__mp__ = v;
          this.dependingOnMainProperty = `foo ${v} bar`;
        }
      }
    };
  }
}

var s = new Sample("a", "b");
s.state.something.mainProperty = "hello";
console.log(s.state.something.dependingOnMainProperty);