gpt4 book ai didi

javascript - Flux React 吞下

转载 作者:行者123 更新时间:2023-12-03 08:11:11 25 4
gpt4 key购买 nike

尝试创建 Flux 存储。当我运行 gulp 并检查我的 index.html 时,出现错误“Uncaught TypeError:监听器必须是函数”

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)

componentDidMount 函数的逻辑如下

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

关于javascript - Flux React 吞下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34139267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com