精简版:
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作为事件处理程序传递而无需手动绑定它。



