[React][flux][EventEmitter] 此引用在组件中更改以存储 ref

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

我有一个组件、一个动作和一个商店,使用 React 和 Flux。

当我将事件从 Store 分派到组件中的方法时,组件中的 "this" ref 更改为 "Store" ref.

你们知道为什么会这样吗?

商店正在此处调度事件,在 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" ref if 不再是我的 "votes" 实例。这会导致下一行的 "this.state" 未定义。

提前致谢。

问题出在你的 class 当你添加你正在调用的 eventListener 时投票 this.updateVote 你应该这样调用这个函数 this.updateVote.bind(this) 当你从你的虚拟 DOM.