Olivier Olivier - 1 month ago 10
React JSX Question

[React][flux][EventEmitter] this reference changes in component to store ref

I have a component, an action and a store, using React & Flux.

When I'm dispatching an event from the Store to a method in my component, "this" ref in my Component changes to the "Store" ref.

Do you guy have any idea of why this is happening?

The store is dispatching event here, in the getAllVotes() method: 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');
}


And the component is handling this event here: https://huit.re/votesL33 where "this" changes to voteStore's ref in the updateVote() method.

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);
}


What I just don't understand is why my "this" ref if not my "votes" instance anymore as soon as the "getAllVotes()" method is called in the store. This causes "this.state" on the below row to be undefined.

Thanks in advance.

Answer

the problem come from your class Vote when you add the eventListener you are calling this.updateVote you should call this function this way this.updateVote.bind(this) as you call a function from your virtual DOM.

Comments