栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

商店的更改侦听器未在componentWillUnmount上移除?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

商店的更改侦听器未在componentWillUnmount上移除?

精简版:

expect(f.bind(this)).not.toBe(f.bind(this));

更长的解释:

问题的原因是,

EventEmitter.removeListener
要求您传递以前注册的功能
EventEmitter.addListener
。如果您传递对任何其他函数的引用,则它是无提示操作。

在您的代码中,您将传递

this._onChange.bind(this)
给addListener。
bind
返回与此绑定的
函数。然后,您将放弃对该绑定函数的引用。然后,您尝试删除由绑定调用创建的另一个 函数,这是一个空操作,因为从未添加过。

React.createClass自动绑定方法。在ES6中,您需要手动绑定您的构造函数:

@AuthenticatedComponentclass ProductsPage extends React.Component {  static propTypes = {    accessToken: PropTypes.string  };  constructor() {    super();    this._productBatch;    this._productBatchesNum;    this._activeProductBatch;    this._productBlacklist;    this._searchById;    this._searchingById;    this.state = this._getStateFromStore();    // Bind listeners (you can write an autoBind(this);    this._onChange = this._onChange.bind(this);  }  componentDidMount() {    // listener pre-bound into a fixed function reference. Add it    ProductsStore.addChangeListener(this._onChange);  }  componentWillUnmount() {    // Remove same function reference that was added    ProductsStore.removeChangeListener(this._onChange);  }  _onChange() {    this.setState(this._getStateFromStore());  }

有多种简化绑定的方法-您可以使用ES7

@autobind
方法装饰器(例如npm上的autobind-
decorator),或编写一个在构造函数中使用调用的autoBind函数
autoBind(this);

在ES7中,您(希望)能够使用类属性来获得更方便的语法。如果您愿意作为阶段1提案http://babeljs.io/docs/plugins/transform-
class-properties/中的
一部分,可以在Babel中启用它。然后,只需将事件侦听器方法声明为类属性,而不是方法:

_onChange = () => {    this.setState(this._getStateFromStore());}

因为_onChange的初始值设定项是在构造函数的上下文中调用的,所以arrow函数会自动绑定

this
到类实例,因此您可以将其
this._onChange
作为事件处理程序传递而无需手动绑定它。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485107.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号