Flux React gulp

Flux React gulp

本文关键字:gulp React Flux      更新时间:2023-09-26

正在尝试创建Flux存储。当我运行gullow并检查我的index.html时,我得到一个错误"Uncaught TypeError:listener must be a function"

var AppDispatcher = require('../dispatchers/app-dispatcher');
var AppConstants = require('../constants/app-constants');
var assign = require('object-assign'); 
var EventEmitterProto = require('events').EventEmitter.prototype;
var CHANGE_EVENT = 'CHANGE'; //broadcast this everytime there is a change
var _catalog = [];
var _cartItems = [];
var AppStore = assign(EventEmitterProto, {
    emitChange: function(){
    this.emit(CHANGE_EVENT)
},
addChangeListener: function(callback){
    this.on(CHANGE_EVENT, callback); //<---if I comment this out code runs perfect
},
removeChangeListener: function(callback){
    this.removeListener(CHANGE_EVENT, callback)
},
getCart: function(){
    return _cartItems
},
getCatalog: function(){
    return _catalog
},
getCartTotals: function(){
    return _cartTotals()
}
});
module.exports = AppStore;

以下是唯一具有侦听器的组件

var React = require('react');
var AppStore = require('../stores/app-store.js');
var RemoveFromCart = require('./app-removefromcart.js'); //this is a component
var Increase = require('./app-increaseitem'); //this is a component
var Decrease = require('./app-decreaseitem'); //this is a component
function cartItems(){
    return {items: AppStore.getCart()}
}
var Catalog = React.createClass({
    getInitialState:function(){
        return cartItems();
    },
    componentWillMount: function(){
        AppStore.addChangeListener(this.onChange)
},
_onChange: function(){
    this.setState(cartItems());
},
render: function(){
    var total = 0;
    var items = this.state.items.map(function(item, i){
        var subtotal = item.cost * item.qty;
        total += subtotal;
            return (
                <tr key={i}>
                    <td><RemoveFromCart /></td>
                    <td>{item.title}</td>
                    <td>{item.qty}</td>
                    <td>
                        <Increase index={i} />
                        <Decrease index={i} />
                    </td>
                    <td>${subtotal}</td>
                </tr>
                );
        })//end map
    return (
        <table className="table table-hover">
            <thead>
                <tr>
                <th></th>
                <th>Item</th>
                <th>Qty</th>
                <th></th>
                <th>Subtotal</th>
                </tr>
            </thead>
            <tbody>
                {items}
            </tbody>
            <tfoot>
                <tr>
                    <td colSpan="4" className="text-right">Total</td>
                </tr>
            </tfoot>
        </table>
        );
}
});
module.exports = Catalog;

请帮忙。这真的很伤我的头

您可能需要更改

AppStore.addChangeListener(this._onChange)

逻辑到组件DidMount函数,如

   componentDidMount:function(){
      AppStore.addChangeListener(this._onChange)
    }