【发布时间】:2016-02-29 23:32:53
【问题描述】:
按照udemy的一个很好的React课程,我使用Reflux创建了一个商店,但是,来自商店的触发事件无法被组件捕获。
我的问题: 为什么在 component.jsx 中使用 ImageStore.orderImage(TODO 1) 不起作用:this.onChange 不会被触发,而 ImageStore.getImage 和 Actions.orderImage 都可以。
感谢您的帮助。
component.jsx 内部:
mixins: [
Reflux.listenTo(ImageStore,'onChange')
],
componentWillMount: function () {
//TODO 1: why ImageStore.orderImage does not work: this.onChange will not be triggered
// ImageStore.orderImage(this.props.params.id); // WHY this does not work? this.onChange will not be triggered.
// ImageStore.getImage(this.props.params.id); // this works
Actions.orderImage(this.props.params.id); // this works, will use this method
},
onChange: function () {
console.log("imageComponent: get a new event from imageStore");
this.setState({
image: ImageStore.findImage(this.props.params.id)
});
}
在 store.jsx 中
listenables: [Actions],
getImage: function (imageID) {
API.get('gallery/image/'+imageID)
.then(function(json){
if(this.images){
this.images.push(json.data);
} else {
this.images = [json.data];
}
this.updateStore();
}.bind(this));
},
orderImage: function (imageID) {
console.log("imageStore: get a new image order:", imageID);
var image = _.findWhere(this.images, {id:imageID});
if (!image) {
this.getImage(imageID);
console.log("imageStore: I start to get image:", imageID);
}
else {
console.log("imageStore: I already have the image:", imageID);
this.trigger('change',this.images);
this.updateStore();
}
},
findImage: function (imageID) {
var image = _.findWhere(this.images, {id:imageID});
if (image) {
return image;
} else {
return null;
}
},
updateStore: function () {
console.log("imageStore: trigger the change");
this.trigger('change',this.images);
}
【问题讨论】: