gpt4 book ai didi

javascript - React mixin 用于向组件添加多个订阅

转载 作者:行者123 更新时间:2023-11-30 08:35:27 30 4
gpt4 key购买 nike

我正在尝试使用 mixin 来订阅/取消订阅我的组件中的消息,我有以下代码,谁能告诉我是否有更好的方法来执行此操作而不是推送每个订阅?

更新:不断出现错误,未捕获类型错误:this.subscribeToChannel 不是函数

提前致谢

var Icon = require('../partials/Icon');
var React = require('react');
var postal = require('postal');

var basketChannel = postal.channel("basket"),
BasketService = require('../../services/BasketService'),
subscriptionsMixin = require('../mixins/subscriptionToChannelsMixin');

var BasketLauncher = React.createClass({

mixins: [subscriptionsMixin],

render: function() {
return (
<button className="pull-right" onClick={this.props.handleClick}>
<Icon type="user" /> {this.getPeopleCount()} People
</button>
);
},

updateBasketTotal: function() {

BasketService.getBasketTotal(function(data){
this.setState({
selectedPeopleCount: data.TotalMembers
});
}.bind(this));
},

componentDidMount: function() {

var comp = this;

comp.updateBasketTotal();

this.subscribeToChannel(basketChannel,"selectAll",function (data) {
BasketService.selectAll(data.selectAll, function () {
comp.updateBasketTotal();
});
});

this.subscriptions.push(
basketChannel.subscribe("updateBasketCount", function () {
comp.updateBasketTotal();
})
);

this.subscriptions.push(
basketChannel.subscribe("removePersonFromBasket", function (data) {
BasketService.removePerson(data.personId,function(){
comp.updateBasketTotal();
});
})
);

this.subscriptions.push(
basketChannel.subscribe("addPersonToBasket", function (data) {
BasketService.addPerson(data.personId,function(){
comp.updateBasketTotal();
} );
})
);

this.subscriptions.push(
basketChannel.subscribe("addArrayToBasket", function (data) {
BasketService.addPerson(data.arrayToPush,function(){
comp.updateBasketTotal();
} );
})
);
},

getPeopleCount: function(){

return this.state.selectedPeopleCount;
},

getInitialState: function() {

return {
subscriptions: [],
selectedPeopleCount:0
};
},

componentWillMount: function() {

var page = this;
}

});

module.exports = BasketLauncher;

混合:

var React = require('react');
var postal = require('postal');

var subscriptionsMixin = {

getInitialState: function() {
return {
subscriptions: []
};
},
componentWillUnmount:function() {
for (i = 0; i < this.subscriptions.length; i++) {
postal.unsubscribe(this.state.subscriptions[i]);
}
},

subscribeToChannel:function(channel,message,callback){
this.state.subscriptions.push(
channel.subscribe(message, callback)
);
}
};

最佳答案

看起来你的 mixin 缺少导出行

module.exports = subscriptionsMixin;

关于javascript - React mixin 用于向组件添加多个订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718603/

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