在reactjs中的EventEmitter.prototype,this.on不起作用,并说它不是一个函数


this.on('change', callback);

this.removeListener('change', callback);

没有在我的addChangeListenerremoveChangeListener上工作.我已经导入了EventEmitter并将其与对象分配("object-assign": "^4.1.1")一起使用。

但它会产生一个错误:

bundle.js:41229 uncatch TypeError: this.on 不是 Object.addChangeListener (bundle.js:41229)at Authors.componentWillMount (bundle.js:40504)at callComponentWillMount (bundle.js:26260)at mountClassInstance (bundle.js:26356)at updateClassComponent (bundle.js:27725)at beginWork (bundle.js:28366)at performUnitOfWork (bundle.js:31198)at workLoop (bundle.js:







31227)
at HTMLUnknownElement.callCallback (bundle.js:19504)
at Object.invokeGuardedCallbackDev (bundle.js:19542)

这是我的代码:

"use strict";
import AppDispatcher from '../dispatcher/AppDispatcher';
import ActionTypes from '../constants/actionTypes';
import { EventEmitter } from 'events';
import assign from 'object-assign';
import _ from 'lodash';
var CHANGE_EVENT = 'change';
var _author = [];
var AuthorStore = assign({}, EventEmitter.protoType, {
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
emitChange() {
this.emit;
},
getAllAuthors() {
return _author;
},
getAuthorById(id) {
return _.find(_author, {
id: id
});
}
});
AppDispatcher.register(function(action) {
switch (action.actionType) {
case ActionTypes.INITIALIZE:
_author = action.initialData.authors;
AuthorStore.emitChange();
break;
case ActionTypes.UPDATE_AUTHOR:
var existingAuthor = _.find(_author, {
id: action.author.id
});
var existingAuthorIndex = _.indexOf(_author, existingAuthor);
_author.splice(existingAuthorIndex, 1, action.author);
AuthorStore.emitChange();
break;
case ActionTypes.CREATE_AUTHOR:
_author.push(action.author);
AuthorStore.emitChange();
break;
case ActionTypes.DELETE_AUTHOR:
_.remove(_author, function(author) {
return action.id === author.id;
});
AuthorStore.emitChange();
break;
default:
}
});
export default AuthorStore;

我不知道为什么它不起作用,我一直在参考这个文档。 谢谢。

我通过将所有项目更改为命名对象属性来解决它,如下所示:

// BEFORE
addChangeListener(callback) {
// AFTER
addChangeListener: function (callback) {
// BEFORE
removeChangeListener(callback) {
// AFTER
removeChangeListener: function (callback) {

。等等。

最新更新