How to Make React.js component listen to a store i

2019-05-04 20:15发布

问题:

I am building an app using React.js and Reflux and I am having trouble getting a component to listen to a store.

First of all, I have successfully linked my store with an event, which looks like this:

Component sends action to store:

var CalcRow = React.createClass({
  handleChange: function(){
        // links to action in store.js
        TodoActions.costChange();
  },
  render: function() {
        return(// redacted)
    }
});

Action:

global.TodoActions = Reflux.createActions([
    "costChange"  // called by individual cost item input    
]);

Store that Recieves the Action:

global.todoListStore = Reflux.createStore({

    listenables: [TodoActions],
    onCostChange: function(){
        alert('test1');
    }
});

Component that Subscribes / listens to the store

var CalcApp = React.createClass({
    mixins: [Reflux.listenTo(todoListStore,"onStatusChange")],
    onStatusChange: function() {
        alert('test2');
    },
        getInitialState: function(){
            return{
                      cat1: this.props.cat1
                  };
         },
  render: function() {
    return (// redacted)
  }
});

I am able to connect the first component (CalcRow) with it's store, and trigger the alert('test1'), but I have not succeeded in making CalcApp listen to the todoListStore and have it fire alert('test2').

I have read the official Reflux docs, but there appears to be something I am missing because CalcApp does not listen to the todoListStore as expected.

Does anyone have any insight into how I can make this (CalcApp) listen to the Reflux store (todoListStore)?

回答1:

Your store doesn't emit anything. You need to call this.trigger:

global.todoListStore = Reflux.createStore({

    listenables: [TodoActions],
    onCostChange: function(){
        this.trigger('test1');
    }
});

docs