简体   繁体   English

EmberJs弃用组件生命周期挂钩didReceiveAttrs

[英]EmberJs deprecate component lifecycle hook didReceiveAttrs

For the Ember version 2.16 , they have removed the arguments passed to the didReceiveAttrs component lifecycle hooks. 对于Ember版本2.16 ,他们已删除传递给didReceiveAttrs组件生命周期挂钩的参数。 Previously I was getting arguments in the form of an object. 以前,我以对象的形式获取参数。

newAttrs:

 EmptyObject: { dataTestId: "test-object" items: MutableCell {__MUTABLE_CELL__ [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: Array(27)} prompt: SafeString {string: "Select an Initiator Group"} required: true selected: MutableCell {__MUTABLE_CELL__ [id=__ember1555539649631463096066386]: true, __REF__ [id=__ember1555539649631670217952659]: RootPropertyReference, value: undefined} __proto__: Object } 

After deprecation how to get such an object in the didReceiveAttrs ? 弃用后,如何在didReceiveAttrs获得这样的对象?

Uh, this was the Deprecation Added in 2.12 . 嗯,这是2.12添加的弃用。 You can get Arguments in Component Lifecycle Hooks until 2.13.0 . 直到2.13.0为止,您都可以在组件生命周期挂钩中获取参数。

An alternative approach for getting the arguments in the hook after 2.13.0 is below, 下面是在2.13.0之后获取挂钩参数的另一种方法,

Before: 之前:

didReceiveAttrs({ oldAttrs, newAttrs }) {
  if (oldAttrs.temp !== newAttrs.temp) {
    this.thermometer.move({ from: oldAttrs.temp, to: newAttrs.temp });
  }
}

After: 后:

didReceiveAttrs() {
  let oldTemp = this.get('_oldTemp');
  let newTemp = this.get('temp');

  if (oldTemp && oldTemp !== newTemp) {
    this.thermometer.move({ from: oldTemp, to: newTemp });
  }
  this.set('_oldTemp', newTemp);
}

You can get more info from the official deprecation guide 您可以从官方弃用指南中获取更多信息

There is ember addon which can provide changed attributes, 有ember插件可以提供更改的属性,

https://github.com/workmanw/ember-diff-attrs https://github.com/workmanw/ember-diff-attrs

Shorthand usage: 速记用法:

import diffAttrs from 'ember-diff-attrs';

export default Ember.Component.extend({
  didReceiveAttrs: diffAttrs('email', 'isAdmin', function(changedAttrs, ...args) {
    this._super(...args);

    if(changedAttrs && changedAttrs.email) {
      let oldEmail = changedAttrs.email[0],
          newEmail = changedAttrs.email[1];
      // Do stuff
    }
  })
});

Extended Usage: 扩展用途:

import diffAttrs from 'ember-diff-attrs';

export default Ember.Component.extend({
  didReceiveAttrs: diffAttrs({
    keys: ['user', 'isAdmin'],
    isEqual(key, a, b) {
      if (key === 'user') {
        return (a && b) ? a.id === b.id : a === b;
      }
      return a === b;
    },
    hook(changedAttrs, ...args) {
      this._super(...args);

      if(changedAttrs && changedAttrs.user) {
        let oldUser = changedAttrs.user[0],
            newUser = changedAttrs.user[1];
        // Do stuff
      }
    }
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM