【问题标题】:[React][flux][EventEmitter] this reference changes in component to store ref[React][flux][EventEmitter] 这个引用在组件中更改以存储 ref
【发布时间】: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


【解决方案1】:

问题来自于你的类投票当你添加你正在调用的事件监听器this.updateVote你应该这样调用这个函数this.updateVote.bind(this)你从你的虚拟DOM调用一个函数。

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 2016-02-18
    • 2016-12-16
    • 2014-10-16
    • 1970-01-01
    • 2021-05-12
    • 2021-02-24
    • 2020-11-29
    相关资源
    最近更新 更多