【发布时间】:2017-02-26 10:03:51
【问题描述】:
我有一个组件、一个动作和一个商店,使用 React 和 Flux。
当我将事件从 Store 分派到组件中的方法时,组件中的“this”引用更改为“Store”引用。
你知道为什么会这样吗?
商店正在这里调度事件,在 getAllVotes() 方法中:https://huit.re/voteStoreRow41
import { EventEmitter } from 'events';
import dispatcher from '../dispatcher/dispatcher.jsx';
import request from 'superagent';
import nocache from 'superagent-no-cache';
const BASE_URL = "http://odu.priv/ws";
class VoteStore extends EventEmitter {
constructor(){
super()
this.votes = [];
this.voteComponent = {};
dispatcher.register(this.handleActions.bind(this));
}
getAll(){
return this.votes;
}
setVotes(listVote){
this.votes.push(listVote);
this.emit('change');
}
getAllVotes(){
this.emit('change');
}
组件在此处处理此事件:https://huit.re/votesL33 其中“this”在 updateVote() 方法中更改为 voteStore 的 ref。
import React from 'react';
import { Vote } from '../vote/vote.jsx';
import voteStore from '../../stores/voteStore.jsx';
import { getAllVote } from '../../actions/voteActions.jsx';
class Votes extends React.Component {
constructor(props) {
super(props);
console.log('const -> ', voteStore);
this.state = {
votes : voteStore.getAll()
};
}
componentWillMount() {
voteStore.on('change', this.updateVote);
getAllVote();
console.log("Votes ", this.state.votes);
}
/*componentWillUnmount() {
voteStore.removeListener('change',this.updateVote);
}*/
updateVote(){
console.log('this -> ',this);
console.log('voteStore -> ',voteStore)
this.setState({
votes : voteStore.getAll()
});
console.log('this.state',this.voteComponent.votes);
}
我只是不明白,一旦在商店中调用“getAllVotes()”方法,为什么我的“this”引用不再是我的“votes”实例。这会导致下一行的“this.state”未定义。
提前致谢。
【问题讨论】:
-
您需要在此处发布问题的最低限度陈述,而不是明天可能会更改或消失的第三方网站。
-
两个链接指向同一行。奇怪的。请更新
-
@Rob 对此感到抱歉。我更新了内容。微小的链接指向我的个人 Git 存储库。毫无疑问,它明天不会消失...... ;) 我只是直接显示正确格式化的代码会更容易,但可以克隆以获得完整的细节。
-
@DamienLeroux 我更新了。对不起。
标签: reactjs dispatcher flux